U
    
W[#                     @   s   d dl mZmZ d dlZd dlmZ d dlmZmZ d dl	m
Z
mZ d dlmZ d dlmZmZ G dd	 d	ZeejG d
d dZdS )    )absolute_importdivisionN)implementer)error
interfaces)clientdns)DNSNameError)nativeStringunicodec                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )"_SRVConnector_ClientFactoryWrapperc                 C   s   || _ || _d S N)-_SRVConnector_ClientFactoryWrapper__connector2_SRVConnector_ClientFactoryWrapper__wrappedFactory)self	connectorZwrappedFactory r   :/usr/lib/python3/dist-packages/twisted/names/srvconnect.py__init__   s    z+_SRVConnector_ClientFactoryWrapper.__init__c                 C   s   | j | j d S r   )r   startedConnectingr   )r   r   r   r   r   r      s    z4_SRVConnector_ClientFactoryWrapper.startedConnectingc                 C   s   | j | d S r   )r   connectionFailedr   r   reasonr   r   r   clientConnectionFailed   s    z9_SRVConnector_ClientFactoryWrapper.clientConnectionFailedc                 C   s   | j | d S r   )r   connectionLostr   r   r   r   clientConnectionLost   s    z7_SRVConnector_ClientFactoryWrapper.clientConnectionLostc                 C   s   t | j|S r   )getattrr   )r   keyr   r   r   __getattr__   s    z._SRVConnector_ClientFactoryWrapper.__getattr__N)__name__
__module____qualname__r   r   r   r   r   r   r   r   r   r      s
   r   c                   @   s   e Zd ZdZdZdddi dfddZd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd ZdS )SRVConnectoraD  
    A connector that looks up DNS SRV records.

    RFC 2782 details how SRV records should be interpreted and selected
    for subsequent connection attempts. The algorithm for using the records'
    priority and weight is implemented in L{pickServer}.

    @ivar servers: List of candidate server records for future connection
        attempts.
    @type servers: L{list} of L{dns.Record_SRV}

    @ivar orderedServers: List of server records that have already been tried
        in this round of connection attempts.
    @type orderedServers: L{list} of L{dns.Record_SRV}
    r   ZtcpZ
connectTCPr   Nc
           
      C   sd   || _ || _t|tr |d}t|| _|| _|| _|| _	|| _
|| _|	| _d| _d| _d| _dS )a  
        @param domain: The domain to connect to.  If passed as a unicode
            string, it will be encoded using C{idna} encoding.
        @type domain: L{bytes} or L{unicode}

        @param defaultPort: Optional default port number to be used when SRV
            lookup fails and the service name is unknown. This should be the
            port number associated with the service name as defined by the IANA
            registry.
        @type defaultPort: L{int}
        ZidnaN)reactorservice
isinstancer   encoder
   domainfactoryprotocolconnectFuncNameconnectFuncArgsconnectFuncKwArgs_defaultPortr   serversorderedServers)
r   r#   r$   r'   r(   r)   r*   r+   r,   ZdefaultPortr   r   r   r   8   s    


zSRVConnector.__init__c                 C   s   | j   | j |  | js| jdkr:| td dS t	dt
| jt
| j| jf }|| j| j || fdd | jr|| j || j n| jdkr|   n
| j  dS )z"Start connection to remote server.NzDomain is not defined.z
_%s._%s.%sc                 S   s   |  S r   )_reallyConnect)xr   r   r   r   <lambda>h       z&SRVConnector.connect.<locals>.<lambda>)r(   ZdoStartr   r.   r'   r   r   DNSLookupErrorr   ZlookupServicer
   r$   r)   ZaddCallbacks_cbGotServers_ebGotServersZaddCallbackr-   Z
addErrback_ebServiceUnknownr   r0   connect)r   dr   r   r   r8   Z   s(    



zSRVConnector.connectc                 C   s   | t g | _g | _d S r   )trapr	   r.   r/   r   Zfailurer   r   r   r6   q   s    
zSRVConnector._ebGotServersc                 C   s   |\}}}t |dkrd|d jtjkrd|d jrd|d jjtdkrdtdt	| j
t	| jf g | _g | _|D ]&}|jtjkst|jsqt| j|j qtd S )N   r      .z'Service %s not available for domain %s.)lentyper   ZSRVZpayloadtargetNamer   r4   reprr$   r'   r.   r/   append)r   resultZanswersZauthaddar   r   r   r5   {   s    
zSRVConnector._cbGotServersc                 C   s6   | tj tdd| j| jg| _g | _| 	  dS )a.  
        Connect to the default port when the service name is unknown.

        If no SRV records were found, the service name will be passed as the
        port. If resolving the name fails with
        L{error.ServiceNameUnknownError}, a final attempt is done using the
        default port.
        r   N)
r:   r   ZServiceNameUnknownErrorr   Z
Record_SRVr-   r'   r.   r/   r8   r;   r   r   r   r7      s    	zSRVConnector._ebServiceUnknownc           	      C   s"  | j dk	st| jdk	st| j s4| js4| j| jfS | j sN| jrN| j| _ g | _| j sXt| j jdd d | j d j}d}d}g }| j D ].}|j|kr||j7 }|||f |d7 }qt	
d|}|D ]B\}}||kr| j | }| j |= | j| t|j|jf  S qtd| jjf dS )a;  
        Pick the next server.

        This selects the next server from the list of SRV records according
        to their priority and weight values, as set out by the default
        algorithm specified in RFC 2782.

        At the beginning of a round, L{servers} is populated with
        L{orderedServers}, and the latter is made empty. L{servers}
        is the list of candidates, and L{orderedServers} is the list of servers
        that have already been tried.

        First, all records are ordered by priority and weight in ascending
        order. Then for each priority level, a running sum is calculated
        over the sorted list of records for that priority. Then a random value
        between 0 and the final sum is compared to each record in order. The
        first record that is greater than or equal to that random value is
        chosen and removed from the list of candidates for this round.

        @return: A tuple of target hostname and port from the chosen DNS SRV
            record.
        @rtype: L{tuple} of native L{str} and L{int}
        Nc                 S   s   | j | jfS r   )priorityweight)recordr   r   r   r2      r3   z)SRVConnector.pickServer.<locals>.<lambda>)r   r   r<   z Impossible %s pickServer result.)r.   AssertionErrorr/   r'   r$   sortrG   rH   rC   randomZrandintstrr@   portRuntimeError	__class__r   )	r   ZminPriorityindexZ	weightSumZweightIndexr1   ZrandrH   Zchosenr   r   r   
pickServer   s8    





zSRVConnector.pickServerc                 C   s|   | j rd| _ d S |  \| _| _| jd k	s2td| jd k	sDtdt| j| j}|| j| jt| | j	f| j
| j| _d S )Nr   zMust have a host to connect to.zMust have a port to connect to.)stopAfterDNSrR   ZhostrN   rJ   r   r#   r*   r   r(   r+   r,   r   )r   ZconnectFuncr   r   r   r0      s      
zSRVConnector._reallyConnectc                 C   s   | j r| j   nd| _dS )zStop attempting to connect.r<   N)r   stopConnectingrS   r   r   r   r   rT      s    zSRVConnector.stopConnectingc                 C   s"   | j dk	r| j   n|   dS )z%Disconnect whatever our are state is.N)r   
disconnectrT   rU   r   r   r   rV      s    
zSRVConnector.disconnectc                 C   s   | j s
t| j  S r   )r   rJ   getDestinationrU   r   r   r   rW      s    
zSRVConnector.getDestinationc                 C   s   | j | | | j   d S r   )r(   r   doStopr   r   r   r   r   r      s    zSRVConnector.connectionFailedc                 C   s   | j | | | j   d S r   )r(   r   rX   rY   r   r   r   r      s    zSRVConnector.connectionLost)r   r    r!   __doc__rS   r   r8   r6   r5   r7   rR   r0   rT   rV   rW   r   r   r   r   r   r   r"   $   s&    
"
>r"   )Z
__future__r   r   rL   Zzope.interfacer   Ztwisted.internetr   r   Ztwisted.namesr   r   Ztwisted.names.errorr	   Ztwisted.python.compatr
   r   r   Z
IConnectorr"   r   r   r   r   <module>   s   