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.

relaymanager.py 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. # -*- test-case-name: twisted.mail.test.test_mail -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Infrastructure for relaying mail through a smart host.
  6. Traditional peer-to-peer email has been increasingly replaced by smart host
  7. configurations. Instead of sending mail directly to the recipient, a sender
  8. sends mail to a smart host. The smart host finds the mail exchange server for
  9. the recipient and sends on the message.
  10. """
  11. import email.utils
  12. import os
  13. import pickle
  14. import time
  15. from typing import Type
  16. from twisted.application import internet
  17. from twisted.internet import protocol
  18. from twisted.internet.defer import Deferred, DeferredList
  19. from twisted.internet.error import DNSLookupError
  20. from twisted.internet.protocol import connectionDone
  21. from twisted.mail import bounce, relay, smtp
  22. from twisted.python import log
  23. from twisted.python.failure import Failure
  24. class ManagedRelayerMixin:
  25. """
  26. SMTP Relayer which notifies a manager
  27. Notify the manager about successful mail, failed mail
  28. and broken connections
  29. """
  30. def __init__(self, manager):
  31. self.manager = manager
  32. @property
  33. def factory(self):
  34. return self._factory
  35. @factory.setter
  36. def factory(self, value):
  37. self._factory = value
  38. def sentMail(self, code, resp, numOk, addresses, log):
  39. """
  40. called when e-mail has been sent
  41. we will always get 0 or 1 addresses.
  42. """
  43. message = self.names[0]
  44. if code in smtp.SUCCESS:
  45. self.manager.notifySuccess(self.factory, message)
  46. else:
  47. self.manager.notifyFailure(self.factory, message)
  48. del self.messages[0]
  49. del self.names[0]
  50. def connectionLost(self, reason: Failure = connectionDone):
  51. """
  52. called when connection is broken
  53. notify manager we will try to send no more e-mail
  54. """
  55. self.manager.notifyDone(self.factory)
  56. class SMTPManagedRelayer(ManagedRelayerMixin, relay.SMTPRelayer): # type: ignore[misc]
  57. """
  58. An SMTP managed relayer.
  59. This managed relayer is an SMTP client which is responsible for sending a
  60. set of messages and keeping an attempt manager informed about its progress.
  61. @type factory: L{SMTPManagedRelayerFactory}
  62. @ivar factory: The factory that created this relayer. This must be set by
  63. the factory.
  64. """
  65. def __init__(self, messages, manager, *args, **kw):
  66. """
  67. @type messages: L{list} of L{bytes}
  68. @param messages: The base filenames of messages to be relayed.
  69. @type manager: L{_AttemptManager}
  70. @param manager: An attempt manager.
  71. @type args: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of
  72. (0) L{bytes}, (1) L{int}
  73. @param args: Positional arguments for L{SMTPClient.__init__}
  74. @type kw: L{dict}
  75. @param kw: Keyword arguments for L{SMTPClient.__init__}
  76. """
  77. ManagedRelayerMixin.__init__(self, manager)
  78. relay.SMTPRelayer.__init__(self, messages, *args, **kw)
  79. class ESMTPManagedRelayer(ManagedRelayerMixin, relay.ESMTPRelayer): # type: ignore[misc]
  80. """
  81. An ESMTP managed relayer.
  82. This managed relayer is an ESMTP client which is responsible for sending a
  83. set of messages and keeping an attempt manager informed about its progress.
  84. """
  85. def __init__(self, messages, manager, *args, **kw):
  86. """
  87. @type messages: L{list} of L{bytes}
  88. @param messages: The base filenames of messages to be relayed.
  89. @type manager: L{_AttemptManager}
  90. @param manager: An attempt manager.
  91. @type args: 3-L{tuple} of (0) L{bytes}, (1) L{None} or
  92. L{ClientContextFactory
  93. <twisted.internet.ssl.ClientContextFactory>}, (2) L{bytes} or
  94. 4-L{tuple} of (0) L{bytes}, (1) L{None} or
  95. L{ClientContextFactory
  96. <twisted.internet.ssl.ClientContextFactory>}, (2) L{bytes},
  97. (3) L{int}
  98. @param args: Positional arguments for L{ESMTPClient.__init__}
  99. @type kw: L{dict}
  100. @param kw: Keyword arguments for L{ESMTPClient.__init__}
  101. """
  102. ManagedRelayerMixin.__init__(self, manager)
  103. relay.ESMTPRelayer.__init__(self, messages, *args, **kw)
  104. class SMTPManagedRelayerFactory(protocol.ClientFactory):
  105. """
  106. A factory to create an L{SMTPManagedRelayer}.
  107. This factory creates a managed relayer which relays a set of messages over
  108. SMTP and informs an attempt manager of its progress.
  109. @ivar messages: See L{__init__}
  110. @ivar manager: See L{__init__}
  111. @type protocol: callable which returns L{SMTPManagedRelayer}
  112. @ivar protocol: A callable which returns a managed relayer for SMTP. See
  113. L{SMTPManagedRelayer.__init__} for parameters to the callable.
  114. @type pArgs: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of
  115. (0) L{bytes}, (1), L{int}
  116. @ivar pArgs: Positional arguments for L{SMTPClient.__init__}
  117. @type pKwArgs: L{dict}
  118. @ivar pKwArgs: Keyword arguments for L{SMTPClient.__init__}
  119. """
  120. protocol: "Type[protocol.Protocol]" = SMTPManagedRelayer
  121. def __init__(self, messages, manager, *args, **kw):
  122. """
  123. @type messages: L{list} of L{bytes}
  124. @param messages: The base filenames of messages to be relayed.
  125. @type manager: L{_AttemptManager}
  126. @param manager: An attempt manager.
  127. @type args: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of
  128. (0) L{bytes}, (1), L{int}
  129. @param args: Positional arguments for L{SMTPClient.__init__}
  130. @type kw: L{dict}
  131. @param kw: Keyword arguments for L{SMTPClient.__init__}
  132. """
  133. self.messages = messages
  134. self.manager = manager
  135. self.pArgs = args
  136. self.pKwArgs = kw
  137. def buildProtocol(self, addr):
  138. """
  139. Create an L{SMTPManagedRelayer}.
  140. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  141. @param addr: The address of the SMTP server.
  142. @rtype: L{SMTPManagedRelayer}
  143. @return: A managed relayer for SMTP.
  144. """
  145. protocol = self.protocol(
  146. self.messages, self.manager, *self.pArgs, **self.pKwArgs
  147. )
  148. protocol.factory = self
  149. return protocol
  150. def clientConnectionFailed(self, connector, reason):
  151. """
  152. Notify the attempt manager that a connection could not be established.
  153. @type connector: L{IConnector <twisted.internet.interfaces.IConnector>}
  154. provider
  155. @param connector: A connector.
  156. @type reason: L{Failure}
  157. @param reason: The reason the connection attempt failed.
  158. """
  159. self.manager.notifyNoConnection(self)
  160. self.manager.notifyDone(self)
  161. class ESMTPManagedRelayerFactory(SMTPManagedRelayerFactory):
  162. """
  163. A factory to create an L{ESMTPManagedRelayer}.
  164. This factory creates a managed relayer which relays a set of messages over
  165. ESMTP and informs an attempt manager of its progress.
  166. @type protocol: callable which returns L{ESMTPManagedRelayer}
  167. @ivar protocol: A callable which returns a managed relayer for ESMTP. See
  168. L{ESMTPManagedRelayer.__init__} for parameters to the callable.
  169. @ivar secret: See L{__init__}
  170. @ivar contextFactory: See L{__init__}
  171. """
  172. protocol = ESMTPManagedRelayer
  173. def __init__(self, messages, manager, secret, contextFactory, *args, **kw):
  174. """
  175. @type messages: L{list} of L{bytes}
  176. @param messages: The base filenames of messages to be relayed.
  177. @type manager: L{_AttemptManager}
  178. @param manager: An attempt manager.
  179. @type secret: L{bytes}
  180. @param secret: A string for the authentication challenge response.
  181. @type contextFactory: L{None} or
  182. L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}
  183. @param contextFactory: An SSL context factory.
  184. @type args: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of
  185. (0) L{bytes}, (1), L{int}
  186. @param args: Positional arguments for L{SMTPClient.__init__}
  187. @param kw: Keyword arguments for L{SMTPClient.__init__}
  188. """
  189. self.secret = secret
  190. self.contextFactory = contextFactory
  191. SMTPManagedRelayerFactory.__init__(self, messages, manager, *args, **kw)
  192. def buildProtocol(self, addr):
  193. """
  194. Create an L{ESMTPManagedRelayer}.
  195. @type addr: L{IAddress <twisted.internet.interfaces.IAddress>} provider
  196. @param addr: The address of the ESMTP server.
  197. @rtype: L{ESMTPManagedRelayer}
  198. @return: A managed relayer for ESMTP.
  199. """
  200. s = self.secret and self.secret(addr)
  201. protocol = self.protocol(
  202. self.messages,
  203. self.manager,
  204. s,
  205. self.contextFactory,
  206. *self.pArgs,
  207. **self.pKwArgs,
  208. )
  209. protocol.factory = self
  210. return protocol
  211. class Queue:
  212. """
  213. A queue for messages to be relayed.
  214. @ivar directory: See L{__init__}
  215. @type n: L{int}
  216. @ivar n: A number used to form unique filenames.
  217. @type waiting: L{dict} of L{bytes}
  218. @ivar waiting: The base filenames of messages waiting to be relayed.
  219. @type relayed: L{dict} of L{bytes}
  220. @ivar relayed: The base filenames of messages in the process of being
  221. relayed.
  222. @type noisy: L{bool}
  223. @ivar noisy: A flag which determines whether informational log messages
  224. will be generated (C{True}) or not (C{False}).
  225. """
  226. noisy = True
  227. def __init__(self, directory):
  228. """
  229. Initialize non-volatile state.
  230. @type directory: L{bytes}
  231. @param directory: The pathname of the directory holding messages in the
  232. queue.
  233. """
  234. self.directory = directory
  235. self._init()
  236. def _init(self):
  237. """
  238. Initialize volatile state.
  239. """
  240. self.n = 0
  241. self.waiting = {}
  242. self.relayed = {}
  243. self.readDirectory()
  244. def __getstate__(self):
  245. """
  246. Create a representation of the non-volatile state of the queue.
  247. @rtype: L{dict} mapping L{bytes} to L{object}
  248. @return: The non-volatile state of the queue.
  249. """
  250. return {"directory": self.directory}
  251. def __setstate__(self, state):
  252. """
  253. Restore the non-volatile state of the queue and recreate the volatile
  254. state.
  255. @type state: L{dict} mapping L{bytes} to L{object}
  256. @param state: The non-volatile state of the queue.
  257. """
  258. self.__dict__.update(state)
  259. self._init()
  260. def readDirectory(self):
  261. """
  262. Scan the message directory for new messages.
  263. """
  264. for message in os.listdir(self.directory):
  265. # Skip non data files
  266. if message[-2:] != "-D":
  267. continue
  268. self.addMessage(message[:-2])
  269. def getWaiting(self):
  270. """
  271. Return the base filenames of messages waiting to be relayed.
  272. @rtype: L{list} of L{bytes}
  273. @return: The base filenames of messages waiting to be relayed.
  274. """
  275. return self.waiting.keys()
  276. def hasWaiting(self):
  277. """
  278. Return an indication of whether the queue has messages waiting to be
  279. relayed.
  280. @rtype: L{bool}
  281. @return: C{True} if messages are waiting to be relayed. C{False}
  282. otherwise.
  283. """
  284. return len(self.waiting) > 0
  285. def getRelayed(self):
  286. """
  287. Return the base filenames of messages in the process of being relayed.
  288. @rtype: L{list} of L{bytes}
  289. @return: The base filenames of messages in the process of being
  290. relayed.
  291. """
  292. return self.relayed.keys()
  293. def setRelaying(self, message):
  294. """
  295. Mark a message as being relayed.
  296. @type message: L{bytes}
  297. @param message: The base filename of a message.
  298. """
  299. del self.waiting[message]
  300. self.relayed[message] = 1
  301. def setWaiting(self, message):
  302. """
  303. Mark a message as waiting to be relayed.
  304. @type message: L{bytes}
  305. @param message: The base filename of a message.
  306. """
  307. del self.relayed[message]
  308. self.waiting[message] = 1
  309. def addMessage(self, message):
  310. """
  311. Mark a message as waiting to be relayed unless it is in the process of
  312. being relayed.
  313. @type message: L{bytes}
  314. @param message: The base filename of a message.
  315. """
  316. if message not in self.relayed:
  317. self.waiting[message] = 1
  318. if self.noisy:
  319. log.msg("Set " + message + " waiting")
  320. def done(self, message):
  321. """
  322. Remove a message from the queue.
  323. @type message: L{bytes}
  324. @param message: The base filename of a message.
  325. """
  326. message = os.path.basename(message)
  327. os.remove(self.getPath(message) + "-D")
  328. os.remove(self.getPath(message) + "-H")
  329. del self.relayed[message]
  330. def getPath(self, message):
  331. """
  332. Return the full base pathname of a message in the queue.
  333. @type message: L{bytes}
  334. @param message: The base filename of a message.
  335. @rtype: L{bytes}
  336. @return: The full base pathname of the message.
  337. """
  338. return os.path.join(self.directory, message)
  339. def getEnvelope(self, message):
  340. """
  341. Get the envelope for a message.
  342. @type message: L{bytes}
  343. @param message: The base filename of a message.
  344. @rtype: L{list} of two L{bytes}
  345. @return: A list containing the origination and destination addresses
  346. for the message.
  347. """
  348. with self.getEnvelopeFile(message) as f:
  349. return pickle.load(f)
  350. def getEnvelopeFile(self, message):
  351. """
  352. Return the envelope file for a message in the queue.
  353. @type message: L{bytes}
  354. @param message: The base filename of a message.
  355. @rtype: file
  356. @return: The envelope file for the message.
  357. """
  358. return open(os.path.join(self.directory, message + "-H"), "rb")
  359. def createNewMessage(self):
  360. """
  361. Create a new message in the queue.
  362. @rtype: 2-L{tuple} of (0) file, (1) L{FileMessage}
  363. @return: The envelope file and a message receiver for a new message in
  364. the queue.
  365. """
  366. fname = f"{os.getpid()}_{time.time()}_{self.n}_{id(self)}"
  367. self.n = self.n + 1
  368. headerFile = open(os.path.join(self.directory, fname + "-H"), "wb")
  369. tempFilename = os.path.join(self.directory, fname + "-C")
  370. finalFilename = os.path.join(self.directory, fname + "-D")
  371. messageFile = open(tempFilename, "wb")
  372. from twisted.mail.mail import FileMessage
  373. return headerFile, FileMessage(messageFile, tempFilename, finalFilename)
  374. class _AttemptManager:
  375. """
  376. A manager for an attempt to relay a set of messages to a mail exchange
  377. server.
  378. @ivar manager: See L{__init__}
  379. @type _completionDeferreds: L{list} of L{Deferred}
  380. @ivar _completionDeferreds: Deferreds which are to be notified when the
  381. attempt to relay is finished.
  382. """
  383. def __init__(self, manager, noisy=True, reactor=None):
  384. """
  385. @type manager: L{SmartHostSMTPRelayingManager}
  386. @param manager: A smart host.
  387. @type noisy: L{bool}
  388. @param noisy: A flag which determines whether informational log
  389. messages will be generated (L{True}) or not (L{False}).
  390. @type reactor: L{IReactorTime
  391. <twisted.internet.interfaces.IReactorTime>} provider
  392. @param reactor: A reactor which will be used to schedule delayed calls.
  393. """
  394. self.manager = manager
  395. self._completionDeferreds = []
  396. self.noisy = noisy
  397. if not reactor:
  398. from twisted.internet import reactor
  399. self.reactor = reactor
  400. def getCompletionDeferred(self):
  401. """
  402. Return a deferred which will fire when the attempt to relay is
  403. finished.
  404. @rtype: L{Deferred}
  405. @return: A deferred which will fire when the attempt to relay is
  406. finished.
  407. """
  408. self._completionDeferreds.append(Deferred())
  409. return self._completionDeferreds[-1]
  410. def _finish(self, relay, message):
  411. """
  412. Remove a message from the relay queue and from the smart host's list of
  413. messages being relayed.
  414. @type relay: L{SMTPManagedRelayerFactory}
  415. @param relay: The factory for the relayer which sent the message.
  416. @type message: L{bytes}
  417. @param message: The path of the file holding the message.
  418. """
  419. self.manager.managed[relay].remove(os.path.basename(message))
  420. self.manager.queue.done(message)
  421. def notifySuccess(self, relay, message):
  422. """
  423. Remove a message from the relay queue after it has been successfully
  424. sent.
  425. @type relay: L{SMTPManagedRelayerFactory}
  426. @param relay: The factory for the relayer which sent the message.
  427. @type message: L{bytes}
  428. @param message: The path of the file holding the message.
  429. """
  430. if self.noisy:
  431. log.msg("success sending %s, removing from queue" % message)
  432. self._finish(relay, message)
  433. def notifyFailure(self, relay, message):
  434. """
  435. Generate a bounce message for a message which cannot be relayed.
  436. @type relay: L{SMTPManagedRelayerFactory}
  437. @param relay: The factory for the relayer responsible for the message.
  438. @type message: L{bytes}
  439. @param message: The path of the file holding the message.
  440. """
  441. if self.noisy:
  442. log.msg("could not relay " + message)
  443. # Moshe - Bounce E-mail here
  444. # Be careful: if it's a bounced bounce, silently
  445. # discard it
  446. message = os.path.basename(message)
  447. with self.manager.queue.getEnvelopeFile(message) as fp:
  448. from_, to = pickle.load(fp)
  449. from_, to, bounceMessage = bounce.generateBounce(
  450. open(self.manager.queue.getPath(message) + "-D"), from_, to
  451. )
  452. fp, outgoingMessage = self.manager.queue.createNewMessage()
  453. with fp:
  454. pickle.dump([from_, to], fp)
  455. for line in bounceMessage.splitlines():
  456. outgoingMessage.lineReceived(line)
  457. outgoingMessage.eomReceived()
  458. self._finish(relay, self.manager.queue.getPath(message))
  459. def notifyDone(self, relay):
  460. """
  461. When the connection is lost or cannot be established, prepare to
  462. resend unsent messages and fire all deferred which are waiting for
  463. the completion of the attempt to relay.
  464. @type relay: L{SMTPManagedRelayerFactory}
  465. @param relay: The factory for the relayer for the connection.
  466. """
  467. for message in self.manager.managed.get(relay, ()):
  468. if self.noisy:
  469. log.msg("Setting " + message + " waiting")
  470. self.manager.queue.setWaiting(message)
  471. try:
  472. del self.manager.managed[relay]
  473. except KeyError:
  474. pass
  475. notifications = self._completionDeferreds
  476. self._completionDeferreds = None
  477. for d in notifications:
  478. d.callback(None)
  479. def notifyNoConnection(self, relay):
  480. """
  481. When a connection to the mail exchange server cannot be established,
  482. prepare to resend messages later.
  483. @type relay: L{SMTPManagedRelayerFactory}
  484. @param relay: The factory for the relayer meant to use the connection.
  485. """
  486. # Back off a bit
  487. try:
  488. msgs = self.manager.managed[relay]
  489. except KeyError:
  490. log.msg("notifyNoConnection passed unknown relay!")
  491. return
  492. if self.noisy:
  493. log.msg("Backing off on delivery of " + str(msgs))
  494. def setWaiting(queue, messages):
  495. map(queue.setWaiting, messages)
  496. self.reactor.callLater(30, setWaiting, self.manager.queue, msgs)
  497. del self.manager.managed[relay]
  498. class SmartHostSMTPRelayingManager:
  499. """
  500. A smart host which uses SMTP managed relayers to send messages from the
  501. relay queue.
  502. L{checkState} must be called periodically at which time the state of the
  503. relay queue is checked and new relayers are created as needed.
  504. In order to relay a set of messages to a mail exchange server, a smart host
  505. creates an attempt manager and a managed relayer factory for that set of
  506. messages. When a connection is made with the mail exchange server, the
  507. managed relayer factory creates a managed relayer to send the messages.
  508. The managed relayer reports on its progress to the attempt manager which,
  509. in turn, updates the smart host's relay queue and information about its
  510. managed relayers.
  511. @ivar queue: See L{__init__}.
  512. @ivar maxConnections: See L{__init__}.
  513. @ivar maxMessagesPerConnection: See L{__init__}.
  514. @type fArgs: 3-L{tuple} of (0) L{list} of L{bytes},
  515. (1) L{_AttemptManager}, (2) L{bytes} or 4-L{tuple} of (0) L{list}
  516. of L{bytes}, (1) L{_AttemptManager}, (2) L{bytes}, (3) L{int}
  517. @ivar fArgs: Positional arguments for
  518. L{SMTPManagedRelayerFactory.__init__}.
  519. @type fKwArgs: L{dict}
  520. @ivar fKwArgs: Keyword arguments for L{SMTPManagedRelayerFactory.__init__}.
  521. @type factory: callable which returns L{SMTPManagedRelayerFactory}
  522. @ivar factory: A callable which creates a factory for creating a managed
  523. relayer. See L{SMTPManagedRelayerFactory.__init__} for parameters to
  524. the callable.
  525. @type PORT: L{int}
  526. @ivar PORT: The port over which to connect to the SMTP server.
  527. @type mxcalc: L{None} or L{MXCalculator}
  528. @ivar mxcalc: A resource for mail exchange host lookups.
  529. @type managed: L{dict} mapping L{SMTPManagedRelayerFactory} to L{list} of
  530. L{bytes}
  531. @ivar managed: A mapping of factory for a managed relayer to
  532. filenames of messages the managed relayer is responsible for.
  533. """
  534. factory: Type[protocol.ClientFactory] = SMTPManagedRelayerFactory
  535. PORT = 25
  536. mxcalc = None
  537. def __init__(self, queue, maxConnections=2, maxMessagesPerConnection=10):
  538. """
  539. Initialize a smart host.
  540. The default values specify connection limits appropriate for a
  541. low-volume smart host.
  542. @type queue: L{Queue}
  543. @param queue: A relay queue.
  544. @type maxConnections: L{int}
  545. @param maxConnections: The maximum number of concurrent connections to
  546. SMTP servers.
  547. @type maxMessagesPerConnection: L{int}
  548. @param maxMessagesPerConnection: The maximum number of messages for
  549. which a relayer will be given responsibility.
  550. """
  551. self.maxConnections = maxConnections
  552. self.maxMessagesPerConnection = maxMessagesPerConnection
  553. self.managed = {} # SMTP clients we're managing
  554. self.queue = queue
  555. self.fArgs = ()
  556. self.fKwArgs = {}
  557. def __getstate__(self):
  558. """
  559. Create a representation of the non-volatile state of this object.
  560. @rtype: L{dict} mapping L{bytes} to L{object}
  561. @return: The non-volatile state of the queue.
  562. """
  563. dct = self.__dict__.copy()
  564. del dct["managed"]
  565. return dct
  566. def __setstate__(self, state):
  567. """
  568. Restore the non-volatile state of this object and recreate the volatile
  569. state.
  570. @type state: L{dict} mapping L{bytes} to L{object}
  571. @param state: The non-volatile state of the queue.
  572. """
  573. self.__dict__.update(state)
  574. self.managed = {}
  575. def checkState(self):
  576. """
  577. Check the state of the relay queue and, if possible, launch relayers to
  578. handle waiting messages.
  579. @rtype: L{None} or L{Deferred}
  580. @return: No return value if no further messages can be relayed or a
  581. deferred which fires when all of the SMTP connections initiated by
  582. this call have disconnected.
  583. """
  584. self.queue.readDirectory()
  585. if len(self.managed) >= self.maxConnections:
  586. return
  587. if not self.queue.hasWaiting():
  588. return
  589. return self._checkStateMX()
  590. def _checkStateMX(self):
  591. nextMessages = self.queue.getWaiting()
  592. nextMessages.reverse()
  593. exchanges = {}
  594. for msg in nextMessages:
  595. from_, to = self.queue.getEnvelope(msg)
  596. name, addr = email.utils.parseaddr(to)
  597. parts = addr.split("@", 1)
  598. if len(parts) != 2:
  599. log.err("Illegal message destination: " + to)
  600. continue
  601. domain = parts[1]
  602. self.queue.setRelaying(msg)
  603. exchanges.setdefault(domain, []).append(self.queue.getPath(msg))
  604. if len(exchanges) >= (self.maxConnections - len(self.managed)):
  605. break
  606. if self.mxcalc is None:
  607. self.mxcalc = MXCalculator()
  608. relays = []
  609. for (domain, msgs) in exchanges.iteritems():
  610. manager = _AttemptManager(self, self.queue.noisy)
  611. factory = self.factory(msgs, manager, *self.fArgs, **self.fKwArgs)
  612. self.managed[factory] = map(os.path.basename, msgs)
  613. relayAttemptDeferred = manager.getCompletionDeferred()
  614. connectSetupDeferred = self.mxcalc.getMX(domain)
  615. connectSetupDeferred.addCallback(lambda mx: str(mx.name))
  616. connectSetupDeferred.addCallback(self._cbExchange, self.PORT, factory)
  617. connectSetupDeferred.addErrback(
  618. lambda err: (relayAttemptDeferred.errback(err), err)[1]
  619. )
  620. connectSetupDeferred.addErrback(self._ebExchange, factory, domain)
  621. relays.append(relayAttemptDeferred)
  622. return DeferredList(relays)
  623. def _cbExchange(self, address, port, factory):
  624. """
  625. Initiate a connection with a mail exchange server.
  626. This callback function runs after mail exchange server for the domain
  627. has been looked up.
  628. @type address: L{bytes}
  629. @param address: The hostname of a mail exchange server.
  630. @type port: L{int}
  631. @param port: A port number.
  632. @type factory: L{SMTPManagedRelayerFactory}
  633. @param factory: A factory which can create a relayer for the mail
  634. exchange server.
  635. """
  636. from twisted.internet import reactor
  637. reactor.connectTCP(address, port, factory)
  638. def _ebExchange(self, failure, factory, domain):
  639. """
  640. Prepare to resend messages later.
  641. This errback function runs when no mail exchange server for the domain
  642. can be found.
  643. @type failure: L{Failure}
  644. @param failure: The reason the mail exchange lookup failed.
  645. @type factory: L{SMTPManagedRelayerFactory}
  646. @param factory: A factory which can create a relayer for the mail
  647. exchange server.
  648. @type domain: L{bytes}
  649. @param domain: A domain.
  650. """
  651. log.err("Error setting up managed relay factory for " + domain)
  652. log.err(failure)
  653. def setWaiting(queue, messages):
  654. map(queue.setWaiting, messages)
  655. from twisted.internet import reactor
  656. reactor.callLater(30, setWaiting, self.queue, self.managed[factory])
  657. del self.managed[factory]
  658. class SmartHostESMTPRelayingManager(SmartHostSMTPRelayingManager):
  659. """
  660. A smart host which uses ESMTP managed relayers to send messages from the
  661. relay queue.
  662. @type factory: callable which returns L{ESMTPManagedRelayerFactory}
  663. @ivar factory: A callable which creates a factory for creating a managed
  664. relayer. See L{ESMTPManagedRelayerFactory.__init__} for parameters to
  665. the callable.
  666. """
  667. factory = ESMTPManagedRelayerFactory
  668. def _checkState(manager):
  669. """
  670. Prompt a relaying manager to check state.
  671. @type manager: L{SmartHostSMTPRelayingManager}
  672. @param manager: A relaying manager.
  673. """
  674. manager.checkState()
  675. def RelayStateHelper(manager, delay):
  676. """
  677. Set up a periodic call to prompt a relaying manager to check state.
  678. @type manager: L{SmartHostSMTPRelayingManager}
  679. @param manager: A relaying manager.
  680. @type delay: L{float}
  681. @param delay: The number of seconds between calls.
  682. @rtype: L{TimerService <internet.TimerService>}
  683. @return: A service which periodically reminds a relaying manager to check
  684. state.
  685. """
  686. return internet.TimerService(delay, _checkState, manager)
  687. class CanonicalNameLoop(Exception):
  688. """
  689. An error indicating that when trying to look up a mail exchange host, a set
  690. of canonical name records was found which form a cycle and resolution was
  691. abandoned.
  692. """
  693. class CanonicalNameChainTooLong(Exception):
  694. """
  695. An error indicating that when trying to look up a mail exchange host, too
  696. many canonical name records which point to other canonical name records
  697. were encountered and resolution was abandoned.
  698. """
  699. class MXCalculator:
  700. """
  701. A utility for looking up mail exchange hosts and tracking whether they are
  702. working or not.
  703. @type clock: L{IReactorTime <twisted.internet.interfaces.IReactorTime>}
  704. provider
  705. @ivar clock: A reactor which will be used to schedule timeouts.
  706. @type resolver: L{IResolver <twisted.internet.interfaces.IResolver>}
  707. @ivar resolver: A resolver.
  708. @type badMXs: L{dict} mapping L{bytes} to L{float}
  709. @ivar badMXs: A mapping of non-functioning mail exchange hostname to time
  710. at which another attempt at contacting it may be made.
  711. @type timeOutBadMX: L{int}
  712. @ivar timeOutBadMX: Period in seconds between attempts to contact a
  713. non-functioning mail exchange host.
  714. @type fallbackToDomain: L{bool}
  715. @ivar fallbackToDomain: A flag indicating whether to attempt to use the
  716. hostname directly when no mail exchange can be found (C{True}) or
  717. not (C{False}).
  718. """
  719. timeOutBadMX = 60 * 60 # One hour
  720. fallbackToDomain = True
  721. def __init__(self, resolver=None, clock=None):
  722. """
  723. @type resolver: L{IResolver <twisted.internet.interfaces.IResolver>}
  724. provider or L{None}
  725. @param resolver: A resolver.
  726. @type clock: L{IReactorTime <twisted.internet.interfaces.IReactorTime>}
  727. provider or L{None}
  728. @param clock: A reactor which will be used to schedule timeouts.
  729. """
  730. self.badMXs = {}
  731. if resolver is None:
  732. from twisted.names.client import createResolver
  733. resolver = createResolver()
  734. self.resolver = resolver
  735. if clock is None:
  736. from twisted.internet import reactor as clock
  737. self.clock = clock
  738. def markBad(self, mx):
  739. """
  740. Record that a mail exchange host is not currently functioning.
  741. @type mx: L{bytes}
  742. @param mx: The hostname of a mail exchange host.
  743. """
  744. self.badMXs[str(mx)] = self.clock.seconds() + self.timeOutBadMX
  745. def markGood(self, mx):
  746. """
  747. Record that a mail exchange host is functioning.
  748. @type mx: L{bytes}
  749. @param mx: The hostname of a mail exchange host.
  750. """
  751. try:
  752. del self.badMXs[mx]
  753. except KeyError:
  754. pass
  755. def getMX(self, domain, maximumCanonicalChainLength=3):
  756. """
  757. Find the name of a host that acts as a mail exchange server
  758. for a domain.
  759. @type domain: L{bytes}
  760. @param domain: A domain name.
  761. @type maximumCanonicalChainLength: L{int}
  762. @param maximumCanonicalChainLength: The maximum number of unique
  763. canonical name records to follow while looking up the mail exchange
  764. host.
  765. @rtype: L{Deferred} which successfully fires with L{Record_MX}
  766. @return: A deferred which succeeds with the MX record for the mail
  767. exchange server for the domain or fails if none can be found.
  768. """
  769. mailExchangeDeferred = self.resolver.lookupMailExchange(domain)
  770. mailExchangeDeferred.addCallback(self._filterRecords)
  771. mailExchangeDeferred.addCallback(
  772. self._cbMX, domain, maximumCanonicalChainLength
  773. )
  774. mailExchangeDeferred.addErrback(self._ebMX, domain)
  775. return mailExchangeDeferred
  776. def _filterRecords(self, records):
  777. """
  778. Organize the records of a DNS response by record name.
  779. @type records: 3-L{tuple} of (0) L{list} of L{RRHeader
  780. <twisted.names.dns.RRHeader>}, (1) L{list} of L{RRHeader
  781. <twisted.names.dns.RRHeader>}, (2) L{list} of L{RRHeader
  782. <twisted.names.dns.RRHeader>}
  783. @param records: Answer resource records, authority resource records and
  784. additional resource records.
  785. @rtype: L{dict} mapping L{bytes} to L{list} of L{IRecord
  786. <twisted.names.dns.IRecord>} provider
  787. @return: A mapping of record name to record payload.
  788. """
  789. recordBag = {}
  790. for answer in records[0]:
  791. recordBag.setdefault(str(answer.name), []).append(answer.payload)
  792. return recordBag
  793. def _cbMX(self, answers, domain, cnamesLeft):
  794. """
  795. Try to find the mail exchange host for a domain from the given DNS
  796. records.
  797. This will attempt to resolve canonical name record results. It can
  798. recognize loops and will give up on non-cyclic chains after a specified
  799. number of lookups.
  800. @type answers: L{dict} mapping L{bytes} to L{list} of L{IRecord
  801. <twisted.names.dns.IRecord>} provider
  802. @param answers: A mapping of record name to record payload.
  803. @type domain: L{bytes}
  804. @param domain: A domain name.
  805. @type cnamesLeft: L{int}
  806. @param cnamesLeft: The number of unique canonical name records
  807. left to follow while looking up the mail exchange host.
  808. @rtype: L{Record_MX <twisted.names.dns.Record_MX>} or L{Failure}
  809. @return: An MX record for the mail exchange host or a failure if one
  810. cannot be found.
  811. """
  812. # Do this import here so that relaymanager.py doesn't depend on
  813. # twisted.names, only MXCalculator will.
  814. from twisted.names import dns, error
  815. seenAliases = set()
  816. exchanges = []
  817. # Examine the answers for the domain we asked about
  818. pertinentRecords = answers.get(domain, [])
  819. while pertinentRecords:
  820. record = pertinentRecords.pop()
  821. # If it's a CNAME, we'll need to do some more processing
  822. if record.TYPE == dns.CNAME:
  823. # Remember that this name was an alias.
  824. seenAliases.add(domain)
  825. canonicalName = str(record.name)
  826. # See if we have some local records which might be relevant.
  827. if canonicalName in answers:
  828. # Make sure it isn't a loop contained entirely within the
  829. # results we have here.
  830. if canonicalName in seenAliases:
  831. return Failure(CanonicalNameLoop(record))
  832. pertinentRecords = answers[canonicalName]
  833. exchanges = []
  834. else:
  835. if cnamesLeft:
  836. # Request more information from the server.
  837. return self.getMX(canonicalName, cnamesLeft - 1)
  838. else:
  839. # Give up.
  840. return Failure(CanonicalNameChainTooLong(record))
  841. # If it's an MX, collect it.
  842. if record.TYPE == dns.MX:
  843. exchanges.append((record.preference, record))
  844. if exchanges:
  845. exchanges.sort()
  846. for (preference, record) in exchanges:
  847. host = str(record.name)
  848. if host not in self.badMXs:
  849. return record
  850. t = self.clock.seconds() - self.badMXs[host]
  851. if t >= 0:
  852. del self.badMXs[host]
  853. return record
  854. return exchanges[0][1]
  855. else:
  856. # Treat no answers the same as an error - jump to the errback to
  857. # try to look up an A record. This provides behavior described as
  858. # a special case in RFC 974 in the section headed I{Interpreting
  859. # the List of MX RRs}.
  860. return Failure(error.DNSNameError(f"No MX records for {domain!r}"))
  861. def _ebMX(self, failure, domain):
  862. """
  863. Attempt to use the name of the domain directly when mail exchange
  864. lookup fails.
  865. @type failure: L{Failure}
  866. @param failure: The reason for the lookup failure.
  867. @type domain: L{bytes}
  868. @param domain: The domain name.
  869. @rtype: L{Record_MX <twisted.names.dns.Record_MX>} or L{Failure}
  870. @return: An MX record for the domain or a failure if the fallback to
  871. domain option is not in effect and an error, other than not
  872. finding an MX record, occurred during lookup.
  873. @raise IOError: When no MX record could be found and the fallback to
  874. domain option is not in effect.
  875. @raise DNSLookupError: When no MX record could be found and the
  876. fallback to domain option is in effect but no address for the
  877. domain could be found.
  878. """
  879. from twisted.names import dns, error
  880. if self.fallbackToDomain:
  881. failure.trap(error.DNSNameError)
  882. log.msg(
  883. "MX lookup failed; attempting to use hostname ({}) directly".format(
  884. domain
  885. )
  886. )
  887. # Alright, I admit, this is a bit icky.
  888. d = self.resolver.getHostByName(domain)
  889. def cbResolved(addr):
  890. return dns.Record_MX(name=addr)
  891. def ebResolved(err):
  892. err.trap(error.DNSNameError)
  893. raise DNSLookupError()
  894. d.addCallbacks(cbResolved, ebResolved)
  895. return d
  896. elif failure.check(error.DNSNameError):
  897. raise OSError(f"No MX found for {domain!r}")
  898. return failure