U
    ¹êW[ÍU  ã                   @   s  d Z ddlmZmZ ddlZddlZddlZddlZddlm	Z	m
Z
mZmZmZmZ ddlmZmZmZ eedƒszedƒ‚ddlmZmZmZmZmZmZ dd	lmZmZ dd
lmZm Z m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( zddlm)Z) W n ek
r   dZ)Y nX dd„ Z*eej+ƒG dd„ de,ƒƒZ-G dd„ de,ƒZ.e)rPe-Z-ne.Z-G dd„ de-ej/ƒZ/dd„ Z0G dd„ de,ƒZ1G dd„ de1ej2ƒZ2G dd„ de-ej3ƒZ4G dd „ d ej5ƒZ6eej7ƒG d!d"„ d"e1ej2ƒƒZ8eej9feej:ƒžŽ G d#d$„ d$e8ƒƒZ;dS )%z”
UNIX socket support for Twisted.

End users shouldn't use this module directly - use the reactor APIs instead.

Maintainer: Itamar Shtull-Trauring
é    )ÚdivisionÚabsolute_importN)ÚEINTRÚEMSGSIZEÚEAGAINÚEWOULDBLOCKÚECONNREFUSEDÚENOBUFS)ÚimplementerÚimplementer_onlyÚimplementedByÚAF_UNIXz+UNIX sockets not supported on this platform)ÚmainÚbaseÚtcpÚudpÚerrorÚ
interfaces)ÚprotocolÚaddress)ÚlockfileÚlogÚreflectÚfailure)Ú_coerceToFilesystemEncoding)ÚuntilConcludes)ÚlazyByteSlice)Úsendmsgc                 C   s   t  d| ¡}tjtj|fgS )zh
    Pack an integer into an ancillary data structure suitable for use with
    L{sendmsg.sendmsg}.
    Úi)ÚstructZpackÚsocketÚ
SOL_SOCKETr   Ú
SCM_RIGHTS)ÚfdZpacked© r$   ú7/usr/lib/python3/dist-packages/twisted/internet/unix.pyÚ_ancillaryDescriptor)   s    r&   c                   @   sH   e Zd ZdZdZdZdd„ Zdd„ Zdd	„ Zd
d„ Z	dd„ Z
dd„ ZdS )Ú_SendmsgMixina
  
    Mixin for stream-oriented UNIX transports which uses sendmsg and recvmsg to
    offer additional functionality, such as copying file descriptors into other
    processes.

    @ivar _writeSomeDataBase: The class which provides the basic implementation
        of C{writeSomeData}.  Ultimately this should be a subclass of
        L{twisted.internet.abstract.FileDescriptor}.  Subclasses which mix in
        L{_SendmsgMixin} must define this.

    @ivar _sendmsgQueue: A C{list} of C{int} holding file descriptors which are
        currently buffered before being sent.

    @ivar _fileDescriptorBufferSize: An C{int} giving the maximum number of file
        descriptors to accept and queue for sending before pausing the
        registered producer, if there is one.
    Né@   c                 C   s
   g | _ d S ©N)Ú_sendmsgQueue©Úselfr$   r$   r%   Ú__init__J   s    z_SendmsgMixin.__init__c                 C   s   t | jƒ| jkp| j | ¡S )a¦  
        Determine whether the user-space send buffer for this transport is full
        or not.

        This extends the base determination by adding consideration of how many
        file descriptors need to be sent using L{sendmsg.sendmsg}.  When there
        are more than C{self._fileDescriptorBufferSize}, the buffer is
        considered full.

        @return: C{True} if it is full, C{False} otherwise.
        )Úlenr*   Ú_fileDescriptorBufferSizeÚ_writeSomeDataBaseÚ_isSendBufferFullr+   r$   r$   r%   r1   N   s    
þz_SendmsgMixin._isSendBufferFullc                 C   s    | j  |¡ |  ¡  |  ¡  dS )zY
        Queue the given file descriptor to be sent and start trying to send it.
        N)r*   ÚappendZ_maybePauseProducerZstartWriting)r,   Úfilenor$   r$   r%   ÚsendFileDescriptorf   s    z _SendmsgMixin.sendFileDescriptorc              
   C   s  t | jƒt |ƒkrt ¡ S d}z¦|t | jƒk rÂ| j| }z&ttj| j|||d … t|ƒƒ W nX tjk
r¶ } z8|jd t	t
fkr”| W Y ¢W ¢4S tj W Y ¢
W ¢"S W 5 d}~X Y q X |d7 }q W 5 | jd|…= X t||ƒ}| j | |¡}z
|| W S  tk
r   | Y S X dS )zg
        Send as much of C{data} as possible.  Also send any pending file
        descriptors.
        r   Né   )r.   r*   r   ZFileDescriptorOverrunr   r   r    r&   Úargsr   r	   r   ÚCONNECTION_LOSTr   r0   ÚwriteSomeDataÚ	TypeError)r,   ÚdataÚindexr#   ÚseZlimitedDataÚresultr$   r$   r%   r8   o   s2    	
  þ$

z_SendmsgMixin.writeSomeDatac              
   C   sÈ   zt tj| j| jƒ\}}}W nJ tjk
rf } z*|jd tkrHW Y ¢dS tj	 W Y ¢S W 5 d}~X Y nX |D ]P\}}}|tj
kr–|tjkr–|  |¡ qltjd|  ¡ |  ¡ |  | j¡||d ql|  |¡S )aö  
        Calls {IProtocol.dataReceived} with all available data and
        L{IFileDescriptorReceiver.fileDescriptorReceived} once for each
        received file descriptor in ancillary data.

        This reads up to C{self.bufferSize} bytes of data from its socket, then
        dispatches the data to protocol callbacks to be handled.  If the
        connection is not lost through an error in the underlying recvmsg(),
        this function will return the result of the dataReceived call.
        r   Nzˆ%(protocolName)s (on %(hostAddress)r) received unsupported ancillary data (level=%(cmsgLevel)r, type=%(cmsgType)r) from %(peerAddress)r.)ÚformatÚhostAddressÚpeerAddressÚprotocolNameÚ	cmsgLevelÚcmsgType)r   r   Zrecvmsgr    Z
bufferSizer   r6   r   r   r7   r!   r"   Ú%_ancillaryLevelSOLSOCKETTypeSCMRIGHTSr   ÚmsgÚgetHostÚgetPeerÚ_getLogPrefixr   Z_dataReceived)r,   r:   Z	ancillaryÚflagsr<   rB   rC   ÚcmsgDatar$   r$   r%   ÚdoRead›   s0      ÿ
 
ÿ 
 øz_SendmsgMixin.doReadc                 C   s|   t |ƒd }t d| |¡}tj | j¡rB|D ]}| j |¡ q.n6tj	d|  
¡ |  ¡ |  | j¡d |D ]}t |¡ qhdS )a¼  
        Processes ancillary data with level SOL_SOCKET and type SCM_RIGHTS,
        indicating that the ancillary data payload holds file descriptors.

        Calls L{IFileDescriptorReceiver.fileDescriptorReceived} once for each
        received file descriptor or logs a message if the protocol does not
        implement L{IFileDescriptorReceiver}.

        @param cmsgData: Ancillary data payload.
        @type cmsgData: L{bytes}
        é   r   zˆ%(protocolName)s (on %(hostAddress)r) does not provide IFileDescriptorReceiver; closing file descriptor received (from %(peerAddress)r).)r>   r?   r@   rA   N)r.   r   Zunpackr   ZIFileDescriptorReceiverZ
providedByr   ZfileDescriptorReceivedr   rE   rF   rG   rH   ÚosÚclose)r,   rJ   ZfdCountZfdsr#   r$   r$   r%   rD   Â   s     
úz3_SendmsgMixin._ancillaryLevelSOLSOCKETTypeSCMRIGHTS)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r0   r/   r-   r1   r4   r8   rK   rD   r$   r$   r$   r%   r'   3   s   	,'r'   c                   @   s   e Zd ZdZdS )Ú_UnsupportedSendmsgMixinz
    Behaviorless placeholder used when C{twisted.python.sendmsg} is not
    available, preventing L{IUNIXTransport} from being supported.
    N)rO   rP   rQ   rR   r$   r$   r$   r%   rS   á   s   rS   c                   @   s6   e Zd ZejZdd„ Zedd„ ƒZdd„ Z	dd„ Z
d	S )
ÚServerc              	   C   s*   t  | ¡ tj | |||d f|||¡ d S r)   )r'   r-   r   rT   )r,   Zsockr   ZclientZserverÚ	sessionnoÚreactorr$   r$   r%   r-   ô   s    
zServer.__init__c           	      C   sž   t  |t jt j¡}t | ¡ ¡}| |¡}|dkr>| ¡  dS d}| ||| 	¡ d||ƒ}d|j
jj|j| ¡ f |_d|j
jj|j| ¡ f |_| |¡ |S )a  
        Create a new L{Server} based on an existing connected I{SOCK_STREAM}
        socket.

        Arguments are the same as to L{Server.__init__}, except where noted.

        @param fileDescriptor: An integer file descriptor associated with a
            connected socket.  The socket must be in non-blocking mode.  Any
            additional attributes desired, such as I{FD_CLOEXEC}, must also be
            set already.

        @return: A new instance of C{cls} wrapping the socket given by
            C{fileDescriptor}.
        Nr   z<%s #%s on %s>z%s,%s,%s)r    Úfromfdr   ÚSOCK_STREAMr   ÚUNIXAddressÚgetsocknameZbuildProtocolrN   Zgetpeernamer   Ú	__class__rO   rU   ZrepstrÚlogstrZmakeConnection)	ÚclsZfileDescriptorÚfactoryrV   ÚsktZprotocolAddrÚprotorU   r,   r$   r$   r%   Ú_fromConnectedSocketø   s(    
  ÿ  ÿ
zServer._fromConnectedSocketc                 C   s   t  | j ¡ ¡S r)   ©r   rY   r    rZ   r+   r$   r$   r%   rF     s    zServer.getHostc                 C   s   t  | jpd ¡S r)   )r   rY   Zhostnamer+   r$   r$   r%   rG     s    zServer.getPeerN)rO   rP   rQ   r   rT   r0   r-   Úclassmethodra   rF   rG   r$   r$   r$   r%   rT   ð   s   
!rT   c                 C   s   | dd… dkS )a›  
    Determine whether the given unix socket path is in a filesystem namespace.

    While most PF_UNIX sockets are entries in the filesystem, Linux 2.2 and
    above support PF_UNIX sockets in an "abstract namespace" that does not
    correspond to any path. This function returns C{True} if the given socket
    path is stored in the filesystem and C{False} if the path is in this
    abstract namespace.
    Nr5   )ó    ú r$   )Úpathr$   r$   r%   Ú_inFilesystemNamespace"  s    
rg   c                   @   s   e Zd Zdd„ ZdS )Ú	_UNIXPortc                 C   s   t  | j ¡ ¡S )zV
        Returns a UNIXAddress.

        This indicates the server's address.
        rb   r+   r$   r$   r%   rF   0  s    z_UNIXPort.getHostN)rO   rP   rQ   rF   r$   r$   r$   r%   rh   /  s   rh   c                   @   s^   e Zd ZejZejZeZ	dZ
ddd„Zedd„ ƒZd	d
„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )ÚPortNé2   é¶  r   c                 C   s4   t jj| |  |¡j|||d || _|| _d | _d S )N©rV   )r   ri   r-   Ú
_buildAddrÚnameÚmodeÚwantPIDÚ_preexistingSocket)r,   ZfileNamer^   Úbacklogro   rV   rp   r$   r$   r%   r-   A  s     ÿzPort.__init__c                 C   s.   t  || j| j¡}| | ¡ ||d}||_|S )aé  
        Create a new L{Port} based on an existing listening I{SOCK_STREAM}
        socket.

        Arguments are the same as to L{Port.__init__}, except where noted.

        @param fd: An integer file descriptor associated with a listening
            socket.  The socket must be in non-blocking mode.  Any additional
            attributes desired, such as I{FD_CLOEXEC}, must also be set already.

        @return: A new instance of C{cls} wrapping the socket given by C{fd}.
        rl   )r    rW   ÚaddressFamilyÚ
socketTyperZ   rq   )r]   rV   r#   r^   Úportr,   r$   r$   r%   Ú_fromListeningDescriptorI  s    zPort._fromListeningDescriptorc                 C   s:   t  | jj¡}t| dƒr,d|td| jƒf S d|f S d S )Nr    ú
<%s on %r>Ú ú<%s (not listening)>)r   Úqualr^   r[   Úhasattrr   ru   )r,   ZfactoryNamer$   r$   r%   Ú__repr__\  s    
 
ÿzPort.__repr__c                 C   s
   t  |¡S r)   ©r   rY   )r,   rn   r$   r$   r%   rm   d  s    zPort._buildAddrc              
   C   s\  t j ¡  t d|  | j¡td| jƒf ¡ | j	ršt
 | jd ¡| _| j ¡ s`t d| jd¡‚n:| jjsšz$t t | j¡j¡rŠt | j¡ W n   Y nX | j ¡  z0| jdk	r¾| j}d| _n|  ¡ }| | j¡ W n6 tjk
r
 } zt d| j|¡‚W 5 d}~X Y nNX t| jƒr(t | j| j¡ | | j¡ d| _ || _| jj!| _!d| _"|  #¡  dS )zÐ
        Create and bind my socket, and begin listening on it.

        This is called on unserialization, and must be called after creating a
        server to begin listening on the specified port.
        z%s starting on %rrx   ó   .lockNzCannot acquire lockTéd   )$r   Z_reservedFDZreserver   rE   rH   r^   r   ru   rp   r   ZFilesystemLockÚlockFileÚlockr   ÚCannotListenErrorZcleanÚstatÚS_ISSOCKrM   Úst_modeÚremoveZdoStartrq   ÚcreateInternetSocketÚbindr    rg   Úchmodro   Zlistenrr   Ú	connectedr3   ZnumberAcceptsZstartReading©r,   r_   Úler$   r$   r%   ÚstartListeningg  sD    


þ

ÿ

"
zPort.startListeningc                 C   s   t  dtd| jƒ ¡ dS )z0
        Log message for closing socket
        z(UNIX Port %s Closed)rx   N)r   rE   r   ru   r+   r$   r$   r%   Ú_logConnectionLostMsg›  s    
ÿzPort._logConnectionLostMsgc                 C   s<   t | jƒrt | j¡ | jd k	r*| j ¡  tj | |¡ d S r)   )	rg   ru   rM   Úunlinkr€   Zunlockr   ri   ÚconnectionLost©r,   Úreasonr$   r$   r%   r   £  s
    


zPort.connectionLost)rj   rk   Nr   )rO   rP   rQ   r    r   rs   rX   rt   rT   Z	transportr€   r-   rc   rv   r|   rm   r   rŽ   r   r$   r$   r$   r%   ri   :  s     ÿ

4ri   c                   @   s<   e Zd ZdZejZejZe	j
Zd
dd„Zdd„ Zdd	„ ZdS )ÚClientzA client for Unix sockets.Nr   c                 C   sj   t  | ¡ t |¡j}|| _| | _| _|rPt 	|d ¡sP|  
d d t |¡|¡ |  
| j|  ¡ d |¡ d S )Nr~   )r'   r-   r   rY   rn   Ú	connectorZrealAddressÚaddrr   ZisLockedZ_finishInitr   ZBadFileErrorZ	doConnectr‡   )r,   Úfilenamer”   rV   ÚcheckPIDr$   r$   r%   r-   ²  s    
 ÿzClient.__init__c                 C   s   t  | j¡S r)   )r   rY   r•   r+   r$   r$   r%   rG   ½  s    zClient.getPeerc                 C   s
   t  d ¡S r)   r}   r+   r$   r$   r%   rF   À  s    zClient.getHost)Nr   )rO   rP   rQ   rR   r    r   rs   rX   rt   r   Ú
BaseClientr0   r-   rG   rF   r$   r$   r$   r%   r“   ¬  s   
r“   c                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )Ú	Connectorc                 C   s"   t j | |||¡ || _|| _d S r)   )r   ÚBaseConnectorr-   r   r—   )r,   r   r^   ZtimeoutrV   r—   r$   r$   r%   r-   Å  s    zConnector.__init__c                 C   s   t | j| | j| jƒS r)   )r“   r   rV   r—   r+   r$   r$   r%   Ú_makeTransportÊ  s    zConnector._makeTransportc                 C   s   t  | j ¡S r)   r}   r+   r$   r$   r%   ÚgetDestinationÍ  s    zConnector.getDestinationN)rO   rP   rQ   r-   r›   rœ   r$   r$   r$   r%   r™   Ä  s   r™   c                   @   sJ   e Zd ZdZejZddd„Zdd„ Zd	d
„ Z	dd„ Z
ddd„Zdd„ ZdS )ÚDatagramPortz4
    Datagram UNIX port, listening for packets.
    é    rk   Nc                 C   s    t jj| ||||d || _dS )z.Initialize with address to listen on.
        )ÚmaxPacketSizerV   N)r   ri   r-   ro   )r,   r•   r`   rŸ   ro   rV   r$   r$   r%   r-   Ù  s    zDatagramPort.__init__c                 C   s4   t  | jj¡}t| dƒr&d|| jf S d|f S d S )Nr    rw   ry   )r   rz   r   r[   r{   ru   )r,   rA   r$   r$   r%   r|   à  s    
zDatagramPort.__repr__c              
   C   sª   t  d| jjt| jƒf ¡ z|  ¡ }| jr8| | j¡ W n4 tj	k
rn } zt	 
d | j|¡‚W 5 d }~X Y nX | jrt| jƒrt | j| j¡ d| _|| _| jj| _d S )Nz%s starting on %sr5   )r   rE   r   r[   Úreprru   r‡   rˆ   r    r   r‚   rg   rM   r‰   ro   rŠ   r3   r‹   r$   r$   r%   Ú_bindSocketè  s    "zDatagramPort._bindSocketc              
   C   s€   z| j  ||¡W S  t jk
rz } zJ|jd }|tkrJ|  ||¡ W Y ¢&S |tkr^t d¡‚n|tkrhn‚ W 5 d}~X Y nX dS )zWrite a datagram.r   úmessage too longN)	r    Zsendtor   r6   r   Úwriter   ÚMessageLengthErrorr   )r,   Zdatagramr   r<   Únor$   r$   r%   r£   ÷  s    
zDatagramPort.writec                 C   sl   t  dt| jƒ ¡ tj | |¡ t| dƒr6| j 	¡  d| _
| j ¡  | `| `t| dƒrh| j d¡ | `dS )zCleans up my socket.
        z(Port %s Closed)r   r   ÚdN)r   rE   r    ru   r   ÚBasePortr   r{   r   ZdoStoprŠ   r    rN   r3   r¦   Úcallbackr‘   r$   r$   r%   r   	  s    



zDatagramPort.connectionLostc                 C   s   t  | jj¡d | _d S )Nz (UDP))r   rz   r   r[   r\   r+   r$   r$   r%   Ú	setLogStr  s    zDatagramPort.setLogStr)rž   rk   N)N)rO   rP   rQ   rR   r    r   rs   r-   r|   r¡   r£   r   r©   r$   r$   r$   r%   r   Ñ  s   

r   c                   @   sB   e Zd ZdZddd„Zdd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Z	dS )ÚConnectedDatagramPortz+
    A connected datagram UNIX socket.
    rž   rk   Nc                 C   s.   t |tjƒst‚t | |||||¡ || _d S r)   )Ú
isinstancer   ZConnectedDatagramProtocolÚAssertionErrorr   r-   Ú
remoteaddr)r,   r•   r`   rŸ   ro   ZbindAddressrV   r$   r$   r%   r-   %  s
    ÿzConnectedDatagramPort.__init__c                 C   sB   z"|   ¡  | j | j¡ |  ¡  W n   |  t ¡ ¡ Y nX d S r)   )r¡   r    Zconnectr­   Z_connectToProtocolÚconnectionFailedr   ZFailurer+   r$   r$   r%   r   -  s    z$ConnectedDatagramPort.startListeningc                 C   s   |   ¡  | j |¡ | `dS )z£
        Called when a connection fails. Stop listening on the socket.

        @type reason: L{Failure}
        @param reason: Why the connection failed.
        N)ZstopListeningr   r®   r‘   r$   r$   r%   r®   6  s    z&ConnectedDatagramPort.connectionFailedc              
   C   s²   d}|| j k r®z.| j | j¡\}}|t|ƒ7 }| j |¡ W q tjk
r˜ } z<|jd }|t	t
tfkrrW Y ¢dS |tkr†| j ¡  n‚ W 5 d}~X Y q   t ¡  Y qX qdS )z=
        Called when my socket is ready for reading.
        r   N)ZmaxThroughputr    ZrecvfromrŸ   r.   r   ZdatagramReceivedr   r6   r   r   r   r   ÚconnectionRefusedr   Zdeferr)r,   Úreadr:   r•   r<   r¥   r$   r$   r%   rK   B  s    


zConnectedDatagramPort.doReadc              
   C   s   z| j  |¡W S  t jk
rŠ } z\|jd }|tkrF|  |¡ W Y ¢:S |tkrZt d¡‚n |tkrn| j	 
¡  n|tkrxn‚ W 5 d}~X Y nX dS )z#
        Write a datagram.
        r   r¢   N)r    Úsendr   r6   r   r£   r   r¤   r   r   r¯   r   )r,   r:   r<   r¥   r$   r$   r%   r£   X  s    
zConnectedDatagramPort.writec                 C   s   t  | j¡S r)   )r   rY   r­   r+   r$   r$   r%   rG   o  s    zConnectedDatagramPort.getPeer)rž   rk   NN)
rO   rP   rQ   rR   r-   r   r®   rK   r£   rG   r$   r$   r$   r%   rª     s       ÿ
	rª   )<rR   Z
__future__r   r   rM   rƒ   r    r   Úerrnor   r   r   r   r   r	   Zzope.interfacer
   r   r   r{   ÚImportErrorZtwisted.internetr   r   r   r   r   r   r   r   Ztwisted.pythonr   r   r   r   Ztwisted.python.filepathr   Ztwisted.python.utilr   Ztwisted.python.compatr   r   r&   ZIUNIXTransportÚobjectr'   rS   rT   rg   rh   ri   r˜   r“   rš   r™   ZIUNIXDatagramTransportr   ZIUNIXDatagramConnectedTransportr§   rª   r$   r$   r$   r%   Ú<module>   sN    
 

 .2rMÿ