a
    î½jÄA  ã                   @   sN   d Z ddlT dZdZdZdZdZdZdZdZ	dZ
dZdZdZG dd	„ d	ƒZd
S )z$Idé   )Ú*é    é   é   é   é   c                   @   sÌ   e Zd ZdZd.dd„Zdd„ Zdd„ Zd	d
„ Zdd„ Ze	fdd„Z
dd„ Zd/dd„Zddi fdd„Zddi fdd„Zdd„ Zdd„ Zd0dd„Zd1d d!„Zd"d#„ Zd$d%„ Zd&d'„ Zd(d)„ Zd*d+„ Zd,d-„ ZdS )2ÚSessiona£  
    The Session class instance is used for storing all session-related info like
    credentials, socket/xml stream/session state flags, roster items (in case of
    client type connection) etc.
    Session object have no means of discovering is any info is ready to be read.
    Instead you should use poll() (recomended) or select() methods for this purpose.
    Session can be one of two types: 'server' and 'client'. 'server' session handles
    inbound connection and 'client' one used to create an outbound one.
    Session instance have multitude of internal attributes. The most imporant is the 'peer' one.
    It is set once the peer is authenticated (client).
    Nc                 C   s  || _ |rd| _|| _t| _nd| _d| _t| _|| _|j| _|j	| _
|j| _d| _|j| _d| _|jj| _i | _|| _| jdkrštt ¡ ƒdd… | _nd| _d| _d| _d| _g | _i | _g | _t| _g | _ttt t!fD ]}||j"v rÜ| j #|¡ qÜg | _"d| _$d| _%|  &¡  dS )aI   When the session is created it's type (client/server) is determined from the beginning.
            socket argument is the pre-created socket-like object.
            It must have the following methods: send, recv, fileno, close.
            owner is the 'master' instance that have Dispatcher plugged into it and generally
            will take care about all session events.
            xmlns is the stream namespace that will be used. Client must set this argument
            If server sets this argument than stream will be dropped if opened with some another namespace.
            peer is the name of peer instance. This is the flag that differentiates client session from
            server session. Client must set it to the name of the server that will be connected, server must
            leave this argument alone.
            ÚclientÚserverNr   Úsessionr   Ú )'ÚxmlnsÚTYPÚpeerÚSOCKET_UNCONNECTEDÚ_socket_stateÚSOCKET_ALIVEÚ_sockÚsendÚ_sendÚrecvÚ_recvÚfilenoÚ_registeredÚ
DispatcherZDBG_LINEÚDEBUGZ	_expectedÚ_ownerÚreprÚrandomÚIDÚ
sendbufferÚ_stream_pos_queuedÚ_stream_pos_sentÚdeliver_key_queueÚdeliver_queue_mapÚstanza_queueÚSESSION_NOT_AUTHEDÚ_session_stateÚwaiting_featuresÚNS_TLSÚNS_SASLÚNS_BINDÚ
NS_SESSIONÚfeaturesÚappendÚfeature_in_processÚslave_sessionÚStartStream)ÚselfÚsocketÚownerr   r   Úfeature© r6   úR/Users/admin/.hermes/hermes-agent/venv/lib/python3.9/site-packages/xmpp/session.pyÚ__init__8   sD    
"zSession.__init__c                 C   sb   t | _t ¡ | _d| j_| j| j_| jj| _| j	| j_
| jdkrT| j| j_|  ¡  n
| j| j_dS )zâ This method is used to initialise the internal xml expat parser
            and to send initial stream header (in case of client connection).
            Should be used after initial connection and after every stream restart.r   r	   N)ÚSTREAM__NOT_OPENEDÚ_stream_stateZ	simplexmlZNodeBuilderÚStreamZ_dispatch_depthÚ	_dispatchÚdispatchÚParseÚ_stream_closeÚstream_footer_receivedr   Ú_catch_stream_idÚstream_header_receivedÚ_stream_open©r2   r6   r6   r7   r1   k   s    






zSession.StartStreamc                 C   sh   z|   d¡}W n   d}Y n0 t|ƒrF|  t|  ¡ ƒd | d¡ n|  dd¡ |  t¡ tdƒ‚|S )z‚ Reads all pending incoming data.
            Raises IOError on disconnection.
            Blocks until at least one byte is read.i (  r   ú Úgotz!Socket error while receiving dataÚerrorzPeer disconnected)r   Úlenr   r   r   Úset_socket_stateÚSOCKET_DEADÚIOError)r2   Zreceivedr6   r6   r7   Úreceive{   s    
zSession.receivec                 C   sB   t |tƒr| ¡  d¡}nt|ƒtdƒkr4| d¡}|  |¡ dS )zÈ Put chunk into "immidiatedly send" queue.
            Should only be used for auth/TLS stuff and like.
            If you just want to shedule regular stanza for delivery use enqueue method.
        úutf-8r   N)Ú
isinstanceÚNodeÚ__str__ÚencodeÚtypeÚenqueue)r2   Úchunkr6   r6   r7   ÚsendnowŠ   s    zSession.sendnowc                 C   s<   t |tƒr| j |¡ n|  j|7  _| jtkr8|  ¡  dS )zä Takes Protocol instance as argument.
            Puts stanza into "send" fifo queue. Items into the send queue are hold until
            stream authenticated. After that this method is effectively the same as "sendnow" method.N)rN   ÚProtocolr%   r.   r    r   r   Ú
push_queue)r2   Ústanzar6   r6   r7   rS   “   s    
zSession.enqueuec                 C   sè   | j tks| jtkr€| j | ¡ | jD ]}| jt| j	| |ƒdd q&| j
D ]}| jt||ƒdd qLi g g   | _	| _| _
dS | jtkrä| j
D ]L}| ¡  d¡}|  j|7  _|  jt|ƒ7  _|| j	| j< | j | j¡ qg | _
dS )zä If stream is authenticated than move items from "send" queue to "immidiatedly send" queue.
            Else if the stream is failed then return all queued stanzas with error passed as argument.
            Otherwise do nothing.r   ©ÚtrustedNrM   )r:   ÚSTREAM__CLOSEDr   rJ   r   Zdeactivatesessionr#   r<   ÚErrorr$   r%   r'   ÚSESSION_AUTHEDrP   rQ   r    r!   rH   r.   )r2   Z
failreasonÚkeyrX   Útxtr6   r6   r7   rW   œ   s     



zSession.push_queuec                 C   sÊ   | j rÆz|  | j ¡}W n*   |  t¡ |  dd¡ |  ¡  Y S 0 |  t|  ¡ ƒd | j d|…  d¡ |  j|7  _| j |d… | _ | j| _	| j
rÆ| j	| j
d krÆ| j| j
d = | j
 | j
d ¡ qŽdS )z\ Put the "immidiatedly send" queue content on the wire. Blocks until at least one byte sent.zSocket error while sending datarG   rE   NÚsentr   )r    r   rI   rJ   r   Úterminate_streamr   r   r"   Z_stream_pos_deliveredr#   r$   Úremove)r2   r`   r6   r6   r7   Úflush_queueµ   s    
&zSession.flush_queuer   c                 C   sF   | j  jd7  _| jtks|rB|  | ¡ d¡ ||_| j || ¡S dS )a"   This is callback that is used to pass the received stanza forth to owner's dispatcher
            _if_ the stream is authorised. Otherwise the stanza is just dropped.
            The 'trusted' argument is used to emulate stanza receive.
            This method is used internally.
        r   r=   N)	r   Zpacketsr:   ÚSTREAM__OPENEDr   rP   rZ   r   r=   )r2   rX   rZ   r6   r6   r7   r<   É   s
    zSession._dispatchÚstreamc                 C   s<   d|vs|d s|   t¡S |d | _d|vr8| j | ¡ dS )z[ This callback is used to detect the stream namespace of incoming stream. Used internally. ÚidÚversionN)ra   ÚSTREAM_INVALID_XMLr   r   ZDialback)r2   ÚnsÚtagÚattrsr6   r6   r7   rA   Õ   s    

zSession._catch_stream_idc                 C   s  d}| j dkr|d| j 7 }n<|d| j 7 }d|vrJ|d| jjd  7 }n|d|d  7 }d|v rr|d	|d  7 }| jr€| j}nt}|d
tt|f 7 }d|v s¨| j dkr°|d7 }|  	|d ¡ |  
t¡ | j dkrÖdS |dkrè|  t¡S |tkrú|  t¡S | jj| jkr|  t¡S d|vr(|  t¡S |d | jjvrD|  t¡S |d  ¡ | _| j dkrd|v rtdƒ}t| jv r–|jj t¡ |jjjj t| jv rÐ|jj t¡ | jjjD ]}||jjj_ qºn4t!| jv rê|jj" t!¡ t#| jv r|jj$ t#¡ |  	|¡ dS )a   This callback is used to handle opening stream tag of the incoming stream.
            In the case of client session it just make some validation.
            Server session also sends server headers and if the stream valid the features node.
            Used internally. z5<?xml version="1.0" encoding="utf-8"?>
<stream:streamr	   z to="%s"z id="%s"Útoz
 from="%s"r   zxml:langz xml:lang="%s"z+ xmlns:db="%s" xmlns:stream="%s" xmlns="%s"rg   z version="1.0"ú>Nre   r
   zstream:features)%r   r   r   r   Zservernamesr   Z	NS_SERVERZNS_DIALBACKZ
NS_STREAMSrU   Úset_stream_staterd   ra   rh   ZSTREAM_INVALID_NAMESPACEr;   ZSTREAM_BAD_NAMESPACE_PREFIXZSTREAM_IMPROPER_ADDRESSINGZSTREAM_HOST_UNKNOWNÚlowerZournamerO   r)   r(   ZNTÚstarttlsÚsetNamespaceÚTÚrequiredr*   Z
mechanismsZSASLZ	mechanismr+   Úbindr,   r   )r2   ri   rj   rk   Útextr   r-   Zmecr6   r6   r7   rC   Ü   s@    

zSession._stream_openc                 C   s$   || j vr| j  |¡ |  |¡ dS )z/ Declare some stream feature as activated one. N)r-   r.   Ú	unfeature©r2   r5   r6   r6   r7   r5     s    zSession.featurec                 C   s   || j v r| j  |¡ dS )z‹ Declare some feature as illegal. Illegal features can not be used.
            Example: BIND feature becomes illegal after Non-SASL auth. N)r(   rb   rw   r6   r6   r7   rv   
  s    zSession.unfeaturer   c                 C   sZ   | j tkrdS |  t¡ |  d¡ |  t¡ |  ¡  | j ¡  |rN| j | ¡ |  	¡  dS )zS Write the closing stream tag and destroy the underlaying socket. Used internally. Nz</stream:stream>)
r:   r[   rn   ÚSTREAM__CLOSINGrU   rW   r   Zflush_queuesZunregistersessionÚ_destroy_socket)r2   Ú
unregisterr6   r6   r7   r?     s    



zSession._stream_closec                 C   s¢   | j tkrdS | j tk r,|  t¡ |  ¡  n,|  t¡ tdd}| t¡ | j|dd |r€t	|t
ƒrr|  |¡ n|  t|ƒ¡ | j|d | jrž| j t¡ dS )aƒ   Notify the peer about stream closure.
            Ensure that xmlstream is not brokes - i.e. if the stream isn't opened yet -
            open it before closure.
            If the error condition is specified than create a stream error and send it along with
            closing stream tag.
            Emulate receiving 'unavailable' type presence just before stream closure.
        NÚunavailable)Útypr   rY   )rz   )r:   rx   rd   rn   rC   ZPresencerq   Z	NS_CLIENTr<   rN   rO   rU   Z	ErrorNoder?   r0   ra   ZSTREAM_REMOTE_CONNECTION_FAILED)r2   rG   rz   Úpr6   r6   r7   ra     s    





zSession.terminate_streamc                 C   s:   d| j _d| j _d| j _| j  ¡  | j ¡  |  t¡ dS )zD Break cyclic dependancies to let python's GC free memory right now.N)	r;   r=   r@   rB   Údestroyr   ÚcloserI   rJ   rD   r6   r6   r7   ry   2  s    

zSession._destroy_socketc                 C   s"   | j rtd|| j f ƒ‚|| _ dS )z] Declare some feature as "negotiating now" to prevent other features from start negotiating. zStarting feature %s over %s !N©r/   Ú	Exception©r2   Úfr6   r6   r7   Ústart_feature;  s    zSession.start_featurec                 C   s&   | j |krtd|| j f ƒ‚d| _ dS )zQ Declare some feature as "negotiated" to allow other features start negotiating. z#Stopping feature %s instead of %s !Nr€   r‚   r6   r6   r7   Ústop_feature@  s    zSession.stop_featurec                 C   s   | j |k r|| _ dS )z» Change the underlaying socket state.
            Socket starts with SOCKET_UNCONNECTED state
            and then proceeds (possibly) to SOCKET_ALIVE
            and then to SOCKET_DEAD N)r   ©r2   Znewstater6   r6   r7   rI   E  s    zSession.set_socket_statec                 C   s.   | j |k r*| j tk r$|tkr$| j| _|| _ dS )zÔ Change the session state.
            Session starts with SESSION_NOT_AUTHED state
            and then comes through
            SESSION_AUTHED, SESSION_BOUND, SESSION_OPENED and SESSION_CLOSED states.
        N)r'   r]   r"   r!   r†   r6   r6   r7   Úset_session_stateL  s    

ÿzSession.set_session_statec                 C   s   | j |k r|| _ dS )aA   Change the underlaying XML stream state
            Stream starts with STREAM__NOT_OPENED and then proceeds with
            STREAM__OPENED, STREAM__CLOSING and STREAM__CLOSED states.
            Note that some features (like TLS and SASL)
            requires stream re-start so this state can have non-linear changes. N)r:   r†   r6   r6   r7   rn   W  s    zSession.set_stream_state)NN)r   )r   )Nr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r8   r1   rL   rU   rS   ZERR_RECIPIENT_UNAVAILABLErW   rc   r<   rA   rC   r5   rv   r?   ra   ry   r„   r…   rI   r‡   rn   r6   r6   r6   r7   r   ,   s*   
3		
)

	r   N)Ú__version__Úprotocolr   r   rJ   r9   rd   rx   r[   r&   r]   ZSESSION_BOUNDZSESSION_OPENEDZSESSION_CLOSEDr   r6   r6   r6   r7   Ú<module>   s   
