o bd@spdZddlZddlZddlZddlZddlmZddlm Z ddl m Z ddl m Z mZddlmZddlmZdd lmZmZmZdd lmZdd lmZGd d d ZGdddeejZGdddeejZGddde j Z!Gddde!Z"GdddZ#GdddZ$GdddZ%Gddde%Z&ddZ'd d!Z(Gd"d#d#e)Z*Gd$d%d%e)Z+Gd&d'd'Z,dS)(aI Infrastructure for relaying mail through a smart host. Traditional peer-to-peer email has been increasingly replaced by smart host configurations. Instead of sending mail directly to the recipient, a sender sends mail to a smart host. The smart host finds the mail exchange server for the recipient and sends on the message. N)Type)internet)protocol)Deferred DeferredList)DNSLookupError)connectionDone)bouncerelaysmtp)log)Failurec@sLeZdZdZddZeddZejddZddZe fd e fd d Z d S) ManagedRelayerMixinz SMTP Relayer which notifies a manager Notify the manager about successful mail, failed mail and broken connections cC ||_dSNmanager)selfrr;/usr/lib/python3/dist-packages/twisted/mail/relaymanager.py__init__&s zManagedRelayerMixin.__init__cCs|jSr_factoryrrrrfactory)szManagedRelayerMixin.factorycCrrr)rvaluerrrr-s cCsJ|jd}|tjvr|j|j|n|j|j||jd=|jd=dS)z` called when e-mail has been sent we will always get 0 or 1 addresses. rN)namesr SUCCESSr notifySuccessr notifyFailuremessages)rcoderespnumOk addressesr messagerrrsentMail1s   zManagedRelayerMixin.sentMailreasoncCs|j|jdS)zm called when connection is broken notify manager we will try to send no more e-mail N)r notifyDoner)rr'rrrconnectionLost?sz"ManagedRelayerMixin.connectionLostN) __name__ __module__ __qualname____doc__rpropertyrsetterr&rr r)rrrrrs  rc@eZdZdZddZdS)SMTPManagedRelayeraV An SMTP managed relayer. This managed relayer is an SMTP client which is responsible for sending a set of messages and keeping an attempt manager informed about its progress. @type factory: L{SMTPManagedRelayerFactory} @ivar factory: The factory that created this relayer. This must be set by the factory. cO,t||tjj||g|Ri|dS)a @type messages: L{list} of L{bytes} @param messages: The base filenames of messages to be relayed. @type manager: L{_AttemptManager} @param manager: An attempt manager. @type args: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of (0) L{bytes}, (1) L{int} @param args: Positional arguments for L{SMTPClient.__init__} @type kw: L{dict} @param kw: Keyword arguments for L{SMTPClient.__init__} N)rrr SMTPRelayerrr rargskwrrrrTs  zSMTPManagedRelayer.__init__Nr*r+r,r-rrrrrr1Hs r1c@r0)ESMTPManagedRelayerz An ESMTP managed relayer. This managed relayer is an ESMTP client which is responsible for sending a set of messages and keeping an attempt manager informed about its progress. cOr2)a @type messages: L{list} of L{bytes} @param messages: The base filenames of messages to be relayed. @type manager: L{_AttemptManager} @param manager: An attempt manager. @type args: 3-L{tuple} of (0) L{bytes}, (1) L{None} or L{ClientContextFactory }, (2) L{bytes} or 4-L{tuple} of (0) L{bytes}, (1) L{None} or L{ClientContextFactory }, (2) L{bytes}, (3) L{int} @param args: Positional arguments for L{ESMTPClient.__init__} @type kw: L{dict} @param kw: Keyword arguments for L{ESMTPClient.__init__} N)rrr ESMTPRelayerr4rrrros  zESMTPManagedRelayer.__init__Nr7rrrrr8gs r8c@s6eZdZUdZeZded<ddZddZdd Z d S) SMTPManagedRelayerFactorya A factory to create an L{SMTPManagedRelayer}. This factory creates a managed relayer which relays a set of messages over SMTP and informs an attempt manager of its progress. @ivar messages: See L{__init__} @ivar manager: See L{__init__} @type protocol: callable which returns L{SMTPManagedRelayer} @ivar protocol: A callable which returns a managed relayer for SMTP. See L{SMTPManagedRelayer.__init__} for parameters to the callable. @type pArgs: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of (0) L{bytes}, (1), L{int} @ivar pArgs: Positional arguments for L{SMTPClient.__init__} @type pKwArgs: L{dict} @ivar pKwArgs: Keyword arguments for L{SMTPClient.__init__} zType[protocol.Protocol]rcOs||_||_||_||_dS)a @type messages: L{list} of L{bytes} @param messages: The base filenames of messages to be relayed. @type manager: L{_AttemptManager} @param manager: An attempt manager. @type args: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of (0) L{bytes}, (1), L{int} @param args: Positional arguments for L{SMTPClient.__init__} @type kw: L{dict} @param kw: Keyword arguments for L{SMTPClient.__init__} N)r rpArgspKwArgsr4rrrrs z"SMTPManagedRelayerFactory.__init__cCs,|j|j|jg|jRi|j}||_|S)a  Create an L{SMTPManagedRelayer}. @type addr: L{IAddress } provider @param addr: The address of the SMTP server. @rtype: L{SMTPManagedRelayer} @return: A managed relayer for SMTP. )rr rr;r<r)raddrrrrr buildProtocols z'SMTPManagedRelayerFactory.buildProtocolcCs|j||j|dS)aH Notify the attempt manager that a connection could not be established. @type connector: L{IConnector } provider @param connector: A connector. @type reason: L{Failure} @param reason: The reason the connection attempt failed. N)rnotifyNoConnectionr()r connectorr'rrrclientConnectionFaileds z0SMTPManagedRelayerFactory.clientConnectionFailedN) r*r+r,r-r1r__annotations__rr>rArrrrr:s   r:c@s$eZdZdZeZddZddZdS)ESMTPManagedRelayerFactorya A factory to create an L{ESMTPManagedRelayer}. This factory creates a managed relayer which relays a set of messages over ESMTP and informs an attempt manager of its progress. @type protocol: callable which returns L{ESMTPManagedRelayer} @ivar protocol: A callable which returns a managed relayer for ESMTP. See L{ESMTPManagedRelayer.__init__} for parameters to the callable. @ivar secret: See L{__init__} @ivar contextFactory: See L{__init__} cOs,||_||_tj|||g|Ri|dS)a @type messages: L{list} of L{bytes} @param messages: The base filenames of messages to be relayed. @type manager: L{_AttemptManager} @param manager: An attempt manager. @type secret: L{bytes} @param secret: A string for the authentication challenge response. @type contextFactory: L{None} or L{ClientContextFactory } @param contextFactory: An SSL context factory. @type args: 1-L{tuple} of (0) L{bytes} or 2-L{tuple} of (0) L{bytes}, (1), L{int} @param args: Positional arguments for L{SMTPClient.__init__} @param kw: Keyword arguments for L{SMTPClient.__init__} N)secretcontextFactoryr:r)rr rrDrEr5r6rrrrs z#ESMTPManagedRelayerFactory.__init__cCsB|jo||}|j|j|j||jg|jRi|j}||_|S)a Create an L{ESMTPManagedRelayer}. @type addr: L{IAddress } provider @param addr: The address of the ESMTP server. @rtype: L{ESMTPManagedRelayer} @return: A managed relayer for ESMTP. )rDrr rrEr;r<r)rr=srrrrr>s z(ESMTPManagedRelayerFactory.buildProtocolN)r*r+r,r-r8rrr>rrrrrCs  rCc@seZdZdZdZddZddZddZd d Zd d Z d dZ ddZ ddZ ddZ ddZddZddZddZddZdd Zd!d"Zd#S)$Queuea. A queue for messages to be relayed. @ivar directory: See L{__init__} @type n: L{int} @ivar n: A number used to form unique filenames. @type waiting: L{dict} of L{bytes} @ivar waiting: The base filenames of messages waiting to be relayed. @type relayed: L{dict} of L{bytes} @ivar relayed: The base filenames of messages in the process of being relayed. @type noisy: L{bool} @ivar noisy: A flag which determines whether informational log messages will be generated (C{True}) or not (C{False}). TcCs||_|dS)z Initialize non-volatile state. @type directory: L{bytes} @param directory: The pathname of the directory holding messages in the queue. N) directory_init)rrHrrrr*s zQueue.__init__cCsd|_i|_i|_|dS)z, Initialize volatile state. rN)nwaitingrelayed readDirectoryrrrrrI5s z Queue._initcCs d|jiS)z Create a representation of the non-volatile state of the queue. @rtype: L{dict} mapping L{bytes} to L{object} @return: The non-volatile state of the queue. rH)rHrrrr __getstate__> zQueue.__getstate__cCs|j||dS)z Restore the non-volatile state of the queue and recreate the volatile state. @type state: L{dict} mapping L{bytes} to L{object} @param state: The non-volatile state of the queue. N)__dict__updaterIrstaterrr __setstate__Gs  zQueue.__setstate__cCs:t|jD]}|dddkrq||ddqdS)z> Scan the message directory for new messages. N-D)oslistdirrH addMessagerr%rrrrMRs zQueue.readDirectorycC |jS)z Return the base filenames of messages waiting to be relayed. @rtype: L{list} of L{bytes} @return: The base filenames of messages waiting to be relayed. )rKkeysrrrr getWaiting\rOzQueue.getWaitingcCst|jdkS)z Return an indication of whether the queue has messages waiting to be relayed. @rtype: L{bool} @return: C{True} if messages are waiting to be relayed. C{False} otherwise. r)lenrKrrrr hasWaitinges zQueue.hasWaitingcCr[)z Return the base filenames of messages in the process of being relayed. @rtype: L{list} of L{bytes} @return: The base filenames of messages in the process of being relayed. )rLr\rrrr getRelayedps zQueue.getRelayedcC|j|=d|j|<dS)z Mark a message as being relayed. @type message: L{bytes} @param message: The base filename of a message. N)rKrLrZrrr setRelayingzzQueue.setRelayingcCra)z Mark a message as waiting to be relayed. @type message: L{bytes} @param message: The base filename of a message. rbN)rLrKrZrrr setWaitingrdzQueue.setWaitingcCs8||jvrd|j|<|jrtd|ddSdSdS)z Mark a message as waiting to be relayed unless it is in the process of being relayed. @type message: L{bytes} @param message: The base filename of a message. rbzSet  waitingN)rLrKnoisyr msgrZrrrrYs  zQueue.addMessagecCs@tj|}t||dt||d|j|=dS)z Remove a message from the queue. @type message: L{bytes} @param message: The base filename of a message. rV-HN)rWpathbasenameremovegetPathrLrZrrrdones  z Queue.donecCstj|j|S)z Return the full base pathname of a message in the queue. @type message: L{bytes} @param message: The base filename of a message. @rtype: L{bytes} @return: The full base pathname of the message. )rWrjjoinrHrZrrrrms z Queue.getPathcCs8|| }t|WdS1swYdS)a Get the envelope for a message. @type message: L{bytes} @param message: The base filename of a message. @rtype: L{list} of two L{bytes} @return: A list containing the origination and destination addresses for the message. N)getEnvelopeFilepickleload)rr%frrr getEnvelopes $zQueue.getEnvelopecCsttj|j|ddS)z Return the envelope file for a message in the queue. @type message: L{bytes} @param message: The base filename of a message. @rtype: file @return: The envelope file for the message. rirb)openrWrjrorHrZrrrrps zQueue.getEnvelopeFilecCstdtd|jdt|}|jd|_ttj|j|dd}tj|j|d}tj|j|d}t|d}ddl m }|||||fS) z Create a new message in the queue. @rtype: 2-L{tuple} of (0) file, (1) L{FileMessage} @return: The envelope file and a message receiver for a new message in the queue. _rbriwbz-CrVr) FileMessage) rWgetpidtimerJidrvrjrorHtwisted.mail.mailry)rfname headerFile tempFilename finalFilename messageFileryrrrcreateNewMessages(   zQueue.createNewMessageN)r*r+r,r-rgrrIrNrTrMr]r_r`rcrerYrnrmrtrprrrrrrGs&              rGc@sJeZdZdZdddZddZdd Zd d Zd d ZddZ ddZ dS)_AttemptManagera* A manager for an attempt to relay a set of messages to a mail exchange server. @ivar manager: See L{__init__} @type _completionDeferreds: L{list} of L{Deferred} @ivar _completionDeferreds: Deferreds which are to be notified when the attempt to relay is finished. TNcCs,||_g|_||_|sddlm}||_dS)a @type manager: L{SmartHostSMTPRelayingManager} @param manager: A smart host. @type noisy: L{bool} @param noisy: A flag which determines whether informational log messages will be generated (L{True}) or not (L{False}). @type reactor: L{IReactorTime } provider @param reactor: A reactor which will be used to schedule delayed calls. rreactorN)r_completionDeferredsrgtwisted.internetr)rrrgrrrrrs    z_AttemptManager.__init__cCs|jt|jdS)z Return a deferred which will fire when the attempt to relay is finished. @rtype: L{Deferred} @return: A deferred which will fire when the attempt to relay is finished. )rappendrrrrrgetCompletionDeferreds z%_AttemptManager.getCompletionDeferredcCs,|jj|tj||jj|dS)aY Remove a message from the relay queue and from the smart host's list of messages being relayed. @type relay: L{SMTPManagedRelayerFactory} @param relay: The factory for the relayer which sent the message. @type message: L{bytes} @param message: The path of the file holding the message. N)rmanagedrlrWrjrkqueuernrr r%rrr_finishs z_AttemptManager._finishcCs$|jr td||||dS)aD Remove a message from the relay queue after it has been successfully sent. @type relay: L{SMTPManagedRelayerFactory} @param relay: The factory for the relayer which sent the message. @type message: L{bytes} @param message: The path of the file holding the message. z'success sending %s, removing from queueN)rgr rhrrrrrrs z_AttemptManager.notifySuccessc Cs|jr td|tj|}|jj|}t |\}}Wdn1s)wYt t |jj|d||\}}}|jj\}}|t ||g|Wdn1s^wY|D]}||qg||||jj|dS)a7 Generate a bounce message for a message which cannot be relayed. @type relay: L{SMTPManagedRelayerFactory} @param relay: The factory for the relayer responsible for the message. @type message: L{bytes} @param message: The path of the file holding the message. zcould not relay NrV)rgr rhrWrjrkrrrprqrrr generateBouncervrmrdump splitlines lineReceived eomReceivedr) rr r%fpfrom_to bounceMessageoutgoingMessagelinerrrr+s"     z_AttemptManager.notifyFailurecCs|jj|dD]}|jrtd|d|jj|qz|jj|=Wn ty.Ynw|j }d|_ |D]}| dq7dS)aF When the connection is lost or cannot be established, prepare to resend unsent messages and fire all deferred which are waiting for the completion of the attempt to relay. @type relay: L{SMTPManagedRelayerFactory} @param relay: The factory for the relayer for the connection. rzSetting rfN) rrgetrgr rhrreKeyErrorrcallback)rr r% notificationsdrrrr(Hs   z_AttemptManager.notifyDonecCstz|jj|}WntytdYdSw|jr$tdt|dd}|jd||jj ||jj|=dS)a When a connection to the mail exchange server cannot be established, prepare to resend messages later. @type relay: L{SMTPManagedRelayerFactory} @param relay: The factory for the relayer meant to use the connection. z(notifyNoConnection passed unknown relay!NzBacking off on delivery of cSt|j|dSrmaprerr rrrrepz6_AttemptManager.notifyNoConnection..setWaiting) rrrr rhrgstrr callLaterr)rr msgsrerrrr?^s   z"_AttemptManager.notifyNoConnection)TN) r*r+r,r-rrrrrr(r?rrrrrs   rc@sfeZdZUdZeZeeje d<dZ dZ dddZ d d Z d d Zd dZddZddZddZdS)SmartHostSMTPRelayingManagera A smart host which uses SMTP managed relayers to send messages from the relay queue. L{checkState} must be called periodically at which time the state of the relay queue is checked and new relayers are created as needed. In order to relay a set of messages to a mail exchange server, a smart host creates an attempt manager and a managed relayer factory for that set of messages. When a connection is made with the mail exchange server, the managed relayer factory creates a managed relayer to send the messages. The managed relayer reports on its progress to the attempt manager which, in turn, updates the smart host's relay queue and information about its managed relayers. @ivar queue: See L{__init__}. @ivar maxConnections: See L{__init__}. @ivar maxMessagesPerConnection: See L{__init__}. @type fArgs: 3-L{tuple} of (0) L{list} of L{bytes}, (1) L{_AttemptManager}, (2) L{bytes} or 4-L{tuple} of (0) L{list} of L{bytes}, (1) L{_AttemptManager}, (2) L{bytes}, (3) L{int} @ivar fArgs: Positional arguments for L{SMTPManagedRelayerFactory.__init__}. @type fKwArgs: L{dict} @ivar fKwArgs: Keyword arguments for L{SMTPManagedRelayerFactory.__init__}. @type factory: callable which returns L{SMTPManagedRelayerFactory} @ivar factory: A callable which creates a factory for creating a managed relayer. See L{SMTPManagedRelayerFactory.__init__} for parameters to the callable. @type PORT: L{int} @ivar PORT: The port over which to connect to the SMTP server. @type mxcalc: L{None} or L{MXCalculator} @ivar mxcalc: A resource for mail exchange host lookups. @type managed: L{dict} mapping L{SMTPManagedRelayerFactory} to L{list} of L{bytes} @ivar managed: A mapping of factory for a managed relayer to filenames of messages the managed relayer is responsible for. rN cCs(||_||_i|_||_d|_i|_dS)a Initialize a smart host. The default values specify connection limits appropriate for a low-volume smart host. @type queue: L{Queue} @param queue: A relay queue. @type maxConnections: L{int} @param maxConnections: The maximum number of concurrent connections to SMTP servers. @type maxMessagesPerConnection: L{int} @param maxMessagesPerConnection: The maximum number of messages for which a relayer will be given responsibility. rN)maxConnectionsmaxMessagesPerConnectionrrfArgsfKwArgs)rrrrrrrrs  z%SmartHostSMTPRelayingManager.__init__cCs|j}|d=|S)z Create a representation of the non-volatile state of this object. @rtype: L{dict} mapping L{bytes} to L{object} @return: The non-volatile state of the queue. r)rPcopy)rdctrrrrNs z)SmartHostSMTPRelayingManager.__getstate__cCs|j|i|_dS)z Restore the non-volatile state of this object and recreate the volatile state. @type state: L{dict} mapping L{bytes} to L{object} @param state: The non-volatile state of the queue. N)rPrQrrRrrrrTs  z)SmartHostSMTPRelayingManager.__setstate__cCs4|jt|j|jkrdS|jsdS|S)af Check the state of the relay queue and, if possible, launch relayers to handle waiting messages. @rtype: L{None} or L{Deferred} @return: No return value if no further messages can be relayed or a deferred which fires when all of the SMTP connections initiated by this call have disconnected. N)rrMr^rrr_ _checkStateMXrrrr checkStates  z'SmartHostSMTPRelayingManager.checkStatecs|j}|i}|D]K}|j|\}}tj|\}}|dd}t|dkr3t d|q |d} |j || | g |j|t||jt|jkrXnq |jdurbt|_g} |D]T\} } t||jj} |j| | g|jRi|j} ttjj| |j| <| |j| }|dd||j |j!| |"fdd|"|j#| | | qht$| S)N@rbrzIllegal message destination: cSs t|jSr)rname)mxrrr s z.cs||fdS)Nrb)errbackerrrelayAttemptDeferredrrr s)%rr]reversertemailutils parseaddrsplitr^r rrc setdefaultrrmrrmxcalc MXCalculator iteritemsrrgrrrrrWrjrkrgetMX addCallback _cbExchangePORT addErrback _ebExchanger)r nextMessages exchangesrhrrrr=partsdomainrelaysrrrconnectSetupDeferredrrrrsB        z*SmartHostSMTPRelayingManager._checkStateMXcCsddlm}||||dS)a Initiate a connection with a mail exchange server. This callback function runs after mail exchange server for the domain has been looked up. @type address: L{bytes} @param address: The hostname of a mail exchange server. @type port: L{int} @param port: A port number. @type factory: L{SMTPManagedRelayerFactory} @param factory: A factory which can create a relayer for the mail exchange server. rrN)rr connectTCP)raddressportrrrrrrs z(SmartHostSMTPRelayingManager._cbExchangecCsPtd|t|dd}ddlm}|d||j|j||j|=dS)a Prepare to resend messages later. This errback function runs when no mail exchange server for the domain can be found. @type failure: L{Failure} @param failure: The reason the mail exchange lookup failed. @type factory: L{SMTPManagedRelayerFactory} @param factory: A factory which can create a relayer for the mail exchange server. @type domain: L{bytes} @param domain: A domain. z+Error setting up managed relay factory for cSrrrrrrrre;rz.setWaitingrrrN)r rrrrrr)rfailurerrrerrrrr's    z(SmartHostSMTPRelayingManager._ebExchange)rr)r*r+r,r-r:rrr ClientFactoryrBrrrrNrTrrrrrrrrrws -   & rc@seZdZdZeZdS)SmartHostESMTPRelayingManagera] A smart host which uses ESMTP managed relayers to send messages from the relay queue. @type factory: callable which returns L{ESMTPManagedRelayerFactory} @ivar factory: A callable which creates a factory for creating a managed relayer. See L{ESMTPManagedRelayerFactory.__init__} for parameters to the callable. N)r*r+r,r-rCrrrrrrDs rcCs |dS)z Prompt a relaying manager to check state. @type manager: L{SmartHostSMTPRelayingManager} @param manager: A relaying manager. N)rrrrr _checkStateRs rcCst|t|S)a Set up a periodic call to prompt a relaying manager to check state. @type manager: L{SmartHostSMTPRelayingManager} @param manager: A relaying manager. @type delay: L{float} @param delay: The number of seconds between calls. @rtype: L{TimerService } @return: A service which periodically reminds a relaying manager to check state. )r TimerServicer)rdelayrrrRelayStateHelper\src@eZdZdZdS)CanonicalNameLoopz An error indicating that when trying to look up a mail exchange host, a set of canonical name records was found which form a cycle and resolution was abandoned. Nr*r+r,r-rrrrrmrc@r)CanonicalNameChainTooLongz An error indicating that when trying to look up a mail exchange host, too many canonical name records which point to other canonical name records were encountered and resolution was abandoned. Nrrrrrrurrc@sTeZdZdZdZdZdddZddZd d Zdd d Z ddZ ddZ ddZ dS)ra A utility for looking up mail exchange hosts and tracking whether they are working or not. @type clock: L{IReactorTime } provider @ivar clock: A reactor which will be used to schedule timeouts. @type resolver: L{IResolver } @ivar resolver: A resolver. @type badMXs: L{dict} mapping L{bytes} to L{float} @ivar badMXs: A mapping of non-functioning mail exchange hostname to time at which another attempt at contacting it may be made. @type timeOutBadMX: L{int} @ivar timeOutBadMX: Period in seconds between attempts to contact a non-functioning mail exchange host. @type fallbackToDomain: L{bool} @ivar fallbackToDomain: A flag indicating whether to attempt to use the hostname directly when no mail exchange can be found (C{True}) or not (C{False}). iTNcCsDi|_|durddlm}|}||_|durddlm}||_dS)aU @type resolver: L{IResolver } provider or L{None} @param resolver: A resolver. @type clock: L{IReactorTime } provider or L{None} @param clock: A reactor which will be used to schedule timeouts. Nr)createResolverr)badMXstwisted.names.clientrresolverrrclock)rrrrrrrrs    zMXCalculator.__init__cCs|j|j|jt|<dS)z Record that a mail exchange host is not currently functioning. @type mx: L{bytes} @param mx: The hostname of a mail exchange host. N)rseconds timeOutBadMXrrrrrrrmarkBadszMXCalculator.markBadcCs$z|j|=WdStyYdSw)z Record that a mail exchange host is functioning. @type mx: L{bytes} @param mx: The hostname of a mail exchange host. N)rrrrrrmarkGoods  zMXCalculator.markGoodcCs:|j|}||j||j||||j||S)ad Find the name of a host that acts as a mail exchange server for a domain. @type domain: L{bytes} @param domain: A domain name. @type maximumCanonicalChainLength: L{int} @param maximumCanonicalChainLength: The maximum number of unique canonical name records to follow while looking up the mail exchange host. @rtype: L{Deferred} which successfully fires with L{Record_MX} @return: A deferred which succeeds with the MX record for the mail exchange server for the domain or fails if none can be found. )rlookupMailExchanger_filterRecords_cbMXr_ebMX)rrmaximumCanonicalChainLengthmailExchangeDeferredrrrrs  zMXCalculator.getMXcCs0i}|dD]}|t|jg|jq|S)af Organize the records of a DNS response by record name. @type records: 3-L{tuple} of (0) L{list} of L{RRHeader }, (1) L{list} of L{RRHeader }, (2) L{list} of L{RRHeader } @param records: Answer resource records, authority resource records and additional resource records. @rtype: L{dict} mapping L{bytes} to L{list} of L{IRecord } provider @return: A mapping of record name to record payload. r)rrrrpayload)rrecords recordBaganswerrrrrs zMXCalculator._filterRecordscCs>ddlm}m}t}g}||g}|r^|} | j|jkrN||t | j } | |vr>| |vr7t t | S|| }g}n|rH| | |dSt t| S| j|jkr\|| j| f|s|r||D](\} } t | j } | |jvrx| S|j|j| } | dkr|j| =| Sqf|ddSt |d|S)a Try to find the mail exchange host for a domain from the given DNS records. This will attempt to resolve canonical name record results. It can recognize loops and will give up on non-cyclic chains after a specified number of lookups. @type answers: L{dict} mapping L{bytes} to L{list} of L{IRecord } provider @param answers: A mapping of record name to record payload. @type domain: L{bytes} @param domain: A domain name. @type cnamesLeft: L{int} @param cnamesLeft: The number of unique canonical name records left to follow while looking up the mail exchange host. @rtype: L{Record_MX } or L{Failure} @return: An MX record for the mail exchange host or a failure if one cannot be found. rdnserrorrbzNo MX records for ) twisted.namesrrsetrpopTYPECNAMEaddrrr rrrMXr preferencesortrrr DNSNameError)ranswersr cnamesLeftrr seenAliasesrpertinentRecordsrecord canonicalNamerhosttrrrrsB            zMXCalculator._cbMXcsddlmm|jr3|jtd||j |}fdd}fdd}| |||S| jr@t d||S) aX Attempt to use the name of the domain directly when mail exchange lookup fails. @type failure: L{Failure} @param failure: The reason for the lookup failure. @type domain: L{bytes} @param domain: The domain name. @rtype: L{Record_MX } or L{Failure} @return: An MX record for the domain or a failure if the fallback to domain option is not in effect and an error, other than not finding an MX record, occurred during lookup. @raise IOError: When no MX record could be found and the fallback to domain option is not in effect. @raise DNSLookupError: When no MX record could be found and the fallback to domain option is in effect but no address for the domain could be found. rrz:MX lookup failed; attempting to use hostname ({}) directlycs j|dS)N)r) Record_MX)r=)rrr cbResolvedfs z&MXCalculator._ebMX..cbResolvedcs|jtr)traprrr)rrr ebResolvedis z&MXCalculator._ebMX..ebResolvedzNo MX found for )rrrfallbackToDomainrrr rhformatr getHostByName addCallbackscheckOSError)rrrrr rrrrrBs       zMXCalculator._ebMX)NN)r) r*r+r,r-rrrrrrrrrrrrrr}s   Rr)-r- email.utilsrrWrqr{typingrtwisted.applicationrrrtwisted.internet.deferrrtwisted.internet.errorrtwisted.internet.protocolr twisted.mailr r r twisted.pythonr twisted.python.failurer rr3r1r9r8rr:rCrGrrrrr Exceptionrrrrrrrs>        * KAON