U
    ¹êW[ð—  ã                   @   s  d Z ddlmZmZmZ ddlmZ e ¡ r4edƒ‚ddl	Z	ddl
Z
ddlZddlZddlZddlZddlZddlZddlZzddlZW n ek
r    dZY nX zddlZddlZW n ek
rÎ   dZY nX ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZ dd
l m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* e#j+Z+i Z,dd„ Z-dd„ Z.dd„ Z/dd„ Z0e0ƒ Z1G dd„ de"j2ƒZ3G dd„ de"j2ƒZ4G dd„ de(e5ƒZ6G dd„ de5ƒZ7e7ƒ Z8dd„ Z9ee*ƒG d d!„ d!e6ƒƒZ:ee*ƒG d"d#„ d#e"j2e6ƒƒZ;dS )$z…
UNIX Process management.

Do NOT use this module directly - use reactor.spawnProcess() instead.

Maintainer: Itamar Shtull-Trauring
é    )ÚdivisionÚabsolute_importÚprint_function)Úplatformz^twisted.internet.process does not work on Windows. Use the reactor.spawnProcess() API instead.N)Úimplementer)ÚlogÚfailure)Ú	switchUID)ÚitemsÚrangeÚ_PY3)ÚfdescÚabstractÚerror)ÚCONNECTION_LOSTÚCONNECTION_DONE)ÚBaseProcess)ÚIProcessTransportc                  C   s   t t ¡ ƒD ]} |  ¡  qdS )z(
    Reap all registered processes.
    N)ÚlistÚreapProcessHandlersÚvaluesÚreapProcess)Úprocess© r   ú:/usr/lib/python3/dist-packages/twisted/internet/process.pyÚreapAllProcesses9   s    r   c                 C   sj   | t krtdƒ‚zt | tj¡\}}W n&   t d|  ¡ t ¡  d}Y nX |r^| |¡ n|t | < dS )z²
    Register a process handler for the given pid, in case L{reapAllProcesses}
    is called.

    @param pid: the pid of the process.
    @param process: a process handler.
    z.Try to register an already registered process.úFailed to reap %d:N)	r   ÚRuntimeErrorÚosÚwaitpidÚWNOHANGr   ÚmsgÚerrÚprocessEnded)Úpidr   ZauxPIDÚstatusr   r   r   ÚregisterReapProcessHandlerD   s    
r&   c                 C   s&   | t krt |  |kstdƒ‚t | = dS )zd
    Unregister a process handler previously registered with
    L{registerReapProcessHandler}.
    z+Try to unregister a process not registered.N)r   r   )r$   r   r   r   r   ÚunregisterReapProcessHandler\   s
    
ÿr'   c                  C   sV   t  ¡ \} }t  |d¡ t |gg g d¡\}}}|r:d}nd}t  | ¡ t  |¡ |S )a  
    On some Linux version, write-only pipe are detected as readable. This
    function is here to check if this bug is present or not.

    See L{ProcessWriter.doRead} for a more detailed explanation.

    @return: C{True} if Linux pipe behaviour is broken.
    @rtype : L{bool}
    ó   ar   TF)r   ÚpipeÚwriteÚselectÚclose)ÚrÚwZreadsZwritesZexesZbrokenPipeBehaviorr   r   r   ÚdetectLinuxBrokenPipeBehaviorh   s    


r/   c                   @   sN   e Zd ZdZd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 )ÚProcessWriteraÿ  
    (Internal) Helper class to write into a Process's input pipe.

    I am a helper which describes a selectable asynchronous writer to a
    process's input pipe, including stdin.

    @ivar enableReadHack: A flag which determines how readability on this
        write descriptor will be handled.  If C{True}, then readability may
        indicate the reader for this write descriptor has been closed (ie,
        the connection has been lost).  If C{False}, then readability events
        are ignored.
    é   r   Fc                 C   s–   t j | |¡ t |¡ || _|| _|| _t 	t
 |  ¡ ¡j¡sHd| _n<|rTd| _n0zt
 |  ¡ d¡ W n tk
r‚   d| _Y nX | jr’|  ¡  dS )zJ
        Initialize, specifying a Process instance to connect to.
        FTr   N)r   ÚFileDescriptorÚ__init__r   ÚsetNonBlockingÚprocÚnameÚfdÚstatÚS_ISFIFOr   ÚfstatÚfilenoÚst_modeÚenableReadHackÚreadÚOSErrorÚstartReading)ÚselfÚreactorr5   r6   r;   ÚforceReadHackr   r   r   r3   •   s    
zProcessWriter.__init__c                 C   s   | j S )z<
        Return the fileno() of my process's stdin.
        ©r7   ©rA   r   r   r   r;   µ   s    zProcessWriter.filenoc                 C   s,   t  | j|¡}|t|ƒkr(| jr(|  ¡  |S ©z6
        Write some data to the open process.
        )r   Ú	writeToFDr7   Úlenr=   r@   )rA   ÚdataÚrvr   r   r   ÚwriteSomeData¼   s    zProcessWriter.writeSomeDatac                 C   s   |   ¡  tj | |¡ d S ©N)ÚstopReadingr   r2   r*   ©rA   rI   r   r   r   r*   É   s    zProcessWriter.writec                 C   sJ   | j r>tr8| j}t |g|gg d¡\}}}|r<|r<tS qFtS n|  ¡  dS )a}  
        The only way a write pipe can become "readable" is at EOF, because the
        child has closed it, and we're using a reactor which doesn't
        distinguish between readable and closed (such as the select reactor).

        Except that's not true on linux < 2.6.11. It has the following
        characteristics: write pipe is completely empty => POLLOUT (writable in
        select), write pipe is not completely empty => POLLIN (readable in
        select), write pipe's reader closed => POLLIN|POLLERR (readable and
        writable in select)

        That's what this funky code is for. If linux was not broken, this
        function could be simply "return CONNECTION_LOST".

        BUG: We call select no matter what the reactor.
        If the reactor is pollreactor, and the fd is > 1024, this will fail.
        (only occurs on broken versions of linux, though).
        r   N)r=   ÚbrokenLinuxPipeBehaviorr7   r+   r   rM   )rA   r7   r-   r.   Úxr   r   r   ÚdoReadÎ   s    zProcessWriter.doReadc                 C   s.   t  | j¡ tj | |¡ | j | j|¡ dS )z=
        See abstract.FileDescriptor.connectionLost.
        N)	r   ZsetBlockingr7   r   r2   ÚconnectionLostr5   ÚchildConnectionLostr6   ©rA   Úreasonr   r   r   rR   í   s    zProcessWriter.connectionLostN)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	connectedZicr=   r3   r;   rK   r*   rQ   rR   r   r   r   r   r0   „   s   
 r0   c                   @   sL   e 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d„ ZdS )ÚProcessReaderzx
    ProcessReader

    I am a selectable representation of a process's output pipe, such as
    stdout and stderr.
    Tc                 C   s6   t j | |¡ t |¡ || _|| _|| _|  ¡  dS )zA
        Initialize, specifying a process to connect to.
        N)	r   r2   r3   r   r4   r5   r6   r7   r@   )rA   rB   r5   r6   r;   r   r   r   r3     s    
zProcessReader.__init__c                 C   s   | j S )z=
        Return the fileno() of my process's stderr.
        rD   rE   r   r   r   r;     s    zProcessReader.filenoc                 C   s   |dkst ‚tS )Nó    )ÚAssertionErrorr   rN   r   r   r   rK     s    zProcessReader.writeSomeDatac                 C   s   t  | j| j¡S )z@
        This is called when the pipe becomes readable.
        )r   Ú
readFromFDr7   ÚdataReceivedrE   r   r   r   rQ     s    zProcessReader.doReadc                 C   s   | j  | j|¡ d S rL   )r5   ÚchildDataReceivedr6   rN   r   r   r   r_   &  s    zProcessReader.dataReceivedc                 C   s6   | j r2| js2d| _|  ¡  | j d| jt t¡¡ d S )Nr1   r   )	rZ   ZdisconnectingrM   rB   Z	callLaterrR   r   ZFailurer   rE   r   r   r   ÚloseConnection*  s    ÿzProcessReader.loseConnectionc                 C   s"   t j | |¡ | j | j|¡ dS )zk
        Close my end of the pipe, signal the Process (which signals the
        ProcessProtocol).
        N)r   r2   rR   r5   rS   r6   rT   r   r   r   rR   2  s    zProcessReader.connectionLostN)rV   rW   rX   rY   rZ   r3   r;   rK   rQ   r_   ra   rR   r   r   r   r   r[   û   s   r[   c                   @   sX   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d„ Zdd„ ZdS )Ú_BaseProcessz0
    Base class for Process and PTYProcess.
    Nc              
   C   sš   zTzt  | jt j¡\}}W n6 tk
rP } z|jtjkr>d}n‚ W 5 d}~X Y nX W n(   t d| j ¡ t 	¡  d}Y nX |r–|  
|¡ t|| ƒ dS )a  
        Try to reap a process (without blocking) via waitpid.

        This is called when sigchild is caught or a Process object loses its
        "connection" (stdout is closed) This ought to result in reaping all
        zombie processes, since it will be called twice as often as it needs
        to be.

        (Unfortunately, this is a slightly experimental approach, since
        UNIX has no way to be really sure that your process is going to
        go away w/o blocking.  I don't want to block.)
        Nr   )r   r   r$   r    r?   ÚerrnoZECHILDr   r!   r"   r#   r'   )rA   r$   r%   Úer   r   r   r   C  s    

z_BaseProcess.reapProcessc                 C   sH   d  }}t  |¡rt  |¡}n
t  |¡}|s0|r>t |||¡S t |¡S rL   )r   Ú	WIFEXITEDÚWEXITSTATUSÚWTERMSIGr   ZProcessTerminatedZProcessDone)rA   r%   ZexitCodeZsigr   r   r   Ú
_getReasonb  s    

z_BaseProcess._getReasonc              
   C   sx   |dkrt td|f ƒ}| jdkr(tƒ ‚zt | j|¡ W n8 tk
rr } z|jtjkr`tƒ ‚n‚ W 5 d}~X Y nX dS )a*  
        Send the given signal C{signalID} to the process. It'll translate a
        few signals ('HUP', 'STOP', 'INT', 'KILL', 'TERM') from a string
        representation to its int value, otherwise it'll pass directly the
        value provided

        @type signalID: C{str} or C{int}
        )ZHUPZSTOPZINTZKILLZTERMzSIG%sN)	ÚgetattrÚsignalr$   ÚProcessExitedAlreadyr   Úkillr?   rc   ZESRCH)rA   ZsignalIDrd   r   r   r   ÚsignalProcessm  s    	
z_BaseProcess.signalProcessc                 C   s4   t dtjƒD ]"}t |¡tjkrt |tj¡ qd S ©Nr1   )r   rj   ÚNSIGÚ	getsignalÚSIG_IGNÚSIG_DFL)rA   Z	signalnumr   r   r   Ú_resetSignalDispositionƒ  s    z$_BaseProcess._resetSignalDispositionc              	   K   s   t  ¡ }t  ¡  zt ¡ | _W n   |r2t  ¡  ‚ Y nÐX | jdkrz.t d¡ | j	f |Ž |  
||||||¡ W nˆ   znt dd¡}	d |t|ƒt|ƒ¡}
tr²tj|	dd}	|	 |
¡ tj|	d |	 ¡  td	ƒD ]}t |¡ qØW n   Y nX Y nX t d
¡ |rt  ¡  d| _dS )aÀ  
        Fork and then exec sub-process.

        @param path: the path where to run the new process.
        @type path: L{bytes} or L{unicode}
        @param uid: if defined, the uid used to run the new process.
        @type uid: L{int}
        @param gid: if defined, the gid used to run the new process.
        @type gid: L{int}
        @param executable: the executable to run in a new process.
        @type executable: L{str}
        @param args: arguments used to create the new process.
        @type args: L{list}.
        @param environment: environment used for the new process.
        @type environment: L{dict}.
        @param kwargs: keyword arguments to L{_setupChild} method.
        r   Né   Úwbz,Upon execvpe {0} {1} in environment id {2}
:zutf-8)Úencoding©Úfileé   r1   éÿÿÿÿ)ÚgcÚ	isenabledÚdisabler   Úforkr$   ÚenableÚsysÚsettraceÚ_setupChildÚ
_execChildÚfdopenÚformatÚstrÚidr   ÚioÚTextIOWrapperr*   Ú	tracebackÚ	print_excÚflushr   r,   Ú_exitr%   )rA   ÚpathÚuidÚgidÚ
executableÚargsÚenvironmentÚkwargsZcollectorEnabledÚstderrr!   r7   r   r   r   Ú_fork  sH    
ÿ þ

z_BaseProcess._forkc                 O   s
   t ƒ ‚dS )zB
        Setup the child process. Override in subclasses.
        N)ÚNotImplementedError)rA   r’   r”   r   r   r   r‚   õ  s    z_BaseProcess._setupChildc                 C   sn   |rt  |¡ |dk	s|dk	r\|dkr.t  ¡ }|dkr>t  ¡ }t  d¡ t  d¡ t||ƒ t  |||¡ dS )z?
        The exec() which is done in the forked child.
        Nr   )r   ÚchdirÚgeteuidÚgetegidÚsetuidÚsetgidr	   Úexecvpe)rA   rŽ   r   r   r‘   r’   r“   r   r   r   rƒ   ü  s    



z_BaseProcess._execChildc                 C   s   d| j j| j| jf S )z5
        String representation of a process.
        z<%s pid=%s status=%s>)Ú	__class__rV   r$   r%   rE   r   r   r   Ú__repr__  s     ÿz_BaseProcess.__repr__)rV   rW   rX   rY   r%   r$   r   rh   rm   rs   r–   r‚   rƒ   rŸ   r   r   r   r   rb   <  s   frb   c                   @   sP   e Zd ZdZejZejZeZdd„ Z	dd„ Z
dd„ Zdd	„ Zd
d„ Zdd„ ZdS )Ú_FDDetectorav  
    This class contains the logic necessary to decide which of the available
    system techniques should be used to detect the open file descriptors for
    the current process. The chosen technique gets monkey-patched into the
    _listOpenFDs method of this class so that the detection only needs to occur
    once.

    @ivar listdir: The implementation of listdir to use. This gets overwritten
        by the test cases.
    @ivar getpid: The implementation of getpid to use, returns the PID of the
        running process.
    @ivar openfile: The implementation of open() to use, by default the Python
        builtin.
    c                 C   s   | j | j| jg| _d S rL   )Ú_procFDImplementationÚ_devFDImplementationÚ_fallbackFDImplementationÚ_implementationsrE   r   r   r   r3   +  s     þz_FDDetector.__init__c                 C   s   |   ¡ | _|  ¡ S )zÄ
        Return an iterable of file descriptors which I{may} be open in this
        process.

        This will try to return the fewest possible descriptors without missing
        any.
        )Ú_getImplementationÚ_listOpenFDsrE   r   r   r   r¦   1  s    
z_FDDetector._listOpenFDsc              
   C   sZ   | j D ]N}z
|ƒ }W n   Y qY nX |  dd¡ |ƒ }W 5 Q R X ||kr|  S q|S )a¿  
        Pick a method which gives correct results for C{_listOpenFDs} in this
        runtime environment.

        This involves a lot of very platform-specific checks, some of which may
        be relatively expensive.  Therefore the returned method should be saved
        and re-used, rather than always calling this method to determine what it
        is.

        See the implementation for the details of how a method is selected.
        z	/dev/nullr-   )r¤   Úopenfile)rA   ÚimplZbeforeZafterr   r   r   r¥   =  s    



z_FDDetector._getImplementationc                 C   s   d}dd„ |   |¡D ƒ}|S )z‰
        Simple implementation for systems where /dev/fd actually works.
        See: http://www.freebsd.org/cgi/man.cgi?fdescfs
        z/dev/fdc                 S   s   g | ]}t |ƒ‘qS r   ©Úint©Ú.0r7   r   r   r   Ú
<listcomp>a  s     z4_FDDetector._devFDImplementation.<locals>.<listcomp>)Úlistdir)rA   ÚdnameÚresultr   r   r   r¢   [  s    z _FDDetector._devFDImplementationc                 C   s"   d|   ¡ f }dd„ |  |¡D ƒS )zk
        Simple implementation for systems where /proc/pid/fd exists (we assume
        it works).
        z/proc/%d/fdc                 S   s   g | ]}t |ƒ‘qS r   r©   r«   r   r   r   r­   k  s     z5_FDDetector._procFDImplementation.<locals>.<listcomp>)Úgetpidr®   )rA   r¯   r   r   r   r¡   e  s    z!_FDDetector._procFDImplementationc                 C   sD   zddl }W n tk
r$   d}Y nX td| |j¡d ƒ}t|ƒS )au  
        Fallback implementation where either the resource module can inform us
        about the upper bound of how many FDs to expect, or where we just guess
        a constant maximum if there is no resource module.

        All possible file descriptors from 0 to that upper bound are returned
        with no attempt to exclude invalid file descriptor values.
        r   Ni   r1   )ÚresourceÚImportErrorÚminZ	getrlimitZRLIMIT_NOFILEr   )rA   r²   Zmaxfdsr   r   r   r£   n  s    	
z%_FDDetector._fallbackFDImplementationN)rV   rW   rX   rY   r   r®   r±   Úopenr§   r3   r¦   r¥   r¢   r¡   r£   r   r   r   r   r      s   
	r    c                   C   s   t  ¡ S )zZ
    Use the global detector object to figure out which FD implementation to
    use.
    )Údetectorr¦   r   r   r   r   r¦   †  s    r¦   c                   @   s²   e Zd ZdZdZdZdZdZeZ	e
Zd'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d„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ ZdS )(ÚProcessaÍ  
    An operating-system Process.

    This represents an operating-system process with arbitrary input/output
    pipes connected to it. Those pipes may represent standard input,
    standard output, and standard error, or any other file descriptor.

    On UNIX, this is implemented using fork(), exec(), pipe()
    and fcntl(). These calls may not exist elsewhere so this
    code is not cross-platform. (also, windows can only select
    on sockets...)
    Frz   Nc
              	      sP  |s$d|	  ¡ kst‚d|	  ¡ ks$t‚t | |¡ i | _i }
|	dkrNddddœ}	| j}|rbtd|	ƒ g ‰ ‡ fdd„}i }zöt|	ƒD ]°\}}|rštd| |ƒ |dkrÒ|ƒ \}}|rÀtd	||f ƒ |||< ||
|< q€|dkr|ƒ \}}|rútd	||f ƒ |||< ||
|< q€t|ƒt	ks(td
|f ƒ‚|||< q€|rBtd|ƒ |rRtd|
ƒ | j
|||||||d W n$   ˆ D ]}t |¡ qx‚ Y nX || _t|
ƒD ]l\}}t || ¡ |	| dkrÞ|  || ||¡}|| j|< |	| dkr | j|| ||dd}|| j|< q z| jdk	r(| j | ¡ W n   t ¡  Y nX t| j| ƒ dS )á  
        Spawn an operating-system process.

        This is where the hard work of disconnecting all currently open
        files / forking / executing the new process happens.  (This is
        executed automatically when a Process is instantiated.)

        This will also run the subprocess as a given user ID and group ID, if
        specified.  (Implementation Note: this doesn't support all the arcane
        nuances of setXXuid on UNIX: it will assume that either your effective
        or real UID is 0.)
        r-   r.   N)r   r1   rt   ÚchildFDsc                     s"   t  ¡ \} }ˆ  | |g¡ | |fS rL   )r   r)   Úextend)r-   r.   ©Z_openedPipesr   r   r)   Ì  s    zProcess.__init__.<locals>.pipez[%d]zreadFD=%d, writeFD=%dz%r should be an intÚfdmapÚhelpers)r¼   T)rC   )r   r]   rb   r3   ÚpipesÚdebugÚprintr
   Útyperª   r–   r   r,   ÚprotoÚprocessReaderFactoryÚprocessWriterFactoryÚmakeConnectionr   r"   r&   r$   )rA   rB   r‘   r’   r“   rŽ   rÂ   r   r   r¹   r½   r¿   r)   r¼   ÚchildFDÚtargetZreadFDZwriteFDZparentFDÚreaderÚwriterr   r»   r   r3   ¦  s€    þ 
 
 


 

 
 

ÿ

 ÿzProcess.__init__c                 C   s¨  | j }|rtj}| d¡ | ¡ }tƒ D ]<}||kr6q(|rH|| ¡ krHq(zt |¡ W q(   Y q(X q(|rxt	d||d t
| ¡ ƒD ]¶}|| }||kr¸|r¬t	d| |d t |¡ q„|| ¡ krt |¡}|rèt	d||f |d t |¡ t|ƒD ]\}	}
|
|krú|||	< qú|r.t	d||f |d t ||¡ q„g }| ¡ D ](}||krH|| ¡ krH| |¡ qH|r†t	d||d |D ]}t |¡ qŠ|  ¡  dS )	a  
        fdmap[childFD] = parentFD

        The child wants to end up with 'childFD' attached to what used to be
        the parent's parentFD. As an example, a bash command run like
        'command 2>&1' would correspond to an fdmap of {0:0, 1:1, 2:1}.
        'command >foo.txt' would be {0:0, 1:os.open('foo.txt'), 2:2}.

        This is accomplished in two steps::

            1. close all file descriptors that aren't values of fdmap.  This
               means 0 .. maxfds (or just the open fds within that range, if
               the platform supports '/proc/<pid>/fd').

            2. for each childFD::

                 - if fdmap[childFD] == childFD, the descriptor is already in
                   place.  Make sure the CLOEXEC flag is not set, then delete
                   the entry from fdmap.

                 - if childFD is in fdmap.values(), then the target descriptor
                   is busy. Use os.dup() to move it elsewhere, update all
                   fdmap[childFD] items that point to it, then close the
                   original. Then fall through to the next case.

                 - now fdmap[childFD] is not in fdmap.values(), and is free.
                   Use os.dup2() to move it to the right place, then close the
                   original.
        zstarting _setupChild
r¼   rw   z%d already in placezos.dup(%d) -> %dzos.dup2(%d,%d)ÚoldN)Údebug_childr€   r•   r*   r   r¦   r;   r   r,   rÀ   ÚsortedÚkeysr   Z_unsetCloseOnExecÚdupr
   Údup2Úappendrs   )rA   r¼   r¿   ZerrfdZdestListr7   ZchildrÇ   Z	newtargetÚcÚprÊ   r   r   r   r‚     sZ    

  
 ÿ

 

 zProcess._setupChildc                 C   s   | j |  |¡ d S rL   ©r¾   r*   )rA   rÆ   rI   r   r   r   ÚwriteToChildj  s    zProcess.writeToChildc                 C   s   || j kr| j |  ¡  d S rL   )r¾   ra   )rA   rÆ   r   r   r   ÚcloseChildFDn  s    
zProcess.closeChildFDc                 C   s&   | j  ¡ D ]}t|tƒr
| ¡  q
d S rL   )r¾   Ú
itervaluesÚ
isinstancer[   rM   ©rA   rÒ   r   r   r   ÚpauseProducingw  s    
zProcess.pauseProducingc                 C   s&   | j  ¡ D ]}t|tƒr
| ¡  q
d S rL   )r¾   rÖ   r×   r[   r@   rØ   r   r   r   ÚresumeProducing}  s    
zProcess.resumeProducingc                 C   s   |   d¡ dS )zD
        Call this to close standard input on this process.
        r   N©rÕ   rE   r   r   r   Ú
closeStdinƒ  s    zProcess.closeStdinc                 C   s   |   d¡ d S rn   rÛ   rE   r   r   r   ÚcloseStdoutŠ  s    zProcess.closeStdoutc                 C   s   |   d¡ d S ©Nrt   rÛ   rE   r   r   r   ÚcloseStderrŽ  s    zProcess.closeStderrc                 C   s   |   ¡  |  ¡  |  ¡  d S rL   )rÜ   rß   rÝ   rE   r   r   r   ra   ’  s    zProcess.loseConnectionc                 C   s   d| j kr| j d  |¡ dS ©z’
        Call this to write to standard input on this process.

        NOTE: This will silently lose data if there is no standard input.
        r   NrÓ   rN   r   r   r   r*   ˜  s    
zProcess.writec                 C   s*   d| j kr| j d  ||¡ n| ¡  dS )z¨
        Call this to register producer for standard input.

        If there is no standard input producer.stopProducing() will
        be called immediately.
        r   N)r¾   ÚregisterProducerZstopProducing)rA   ZproducerZ	streamingr   r   r   rá   ¢  s    
zProcess.registerProducerc                 C   s   d| j kr| j d  ¡  dS )z=
        Call this to unregister producer for standard input.r   N)r¾   ÚunregisterProducerrE   r   r   r   râ   ¯  s    
zProcess.unregisterProducerc                 C   s   d| j kr| j d  |¡ dS rà   )r¾   ÚwriteSequence)rA   Úseqr   r   r   rã   ¶  s    
zProcess.writeSequencec                 C   s   | j  ||¡ d S rL   ©rÂ   r`   )rA   r6   rI   r   r   r   r`   À  s    zProcess.childDataReceivedc                 C   sN   t  | j|  ¡ ¡ | j|= z| j |¡ W n   t ¡  Y nX |  ¡  d S rL   )	r   r,   r¾   r;   rÂ   rS   r   r"   ÚmaybeCallProcessEnded)rA   rÆ   rU   r   r   r   rS   Ä  s    zProcess.childConnectionLostc                 C   s*   | j r
d S | js|  ¡  d S t | ¡ d S rL   )r¾   ÚlostProcessr   rb   ræ   rE   r   r   r   ræ   Ð  s    zProcess.maybeCallProcessEnded)NNN)rV   rW   rX   rY   r¿   rË   r%   r$   r0   rÄ   r[   rÃ   r3   r‚   rÔ   rÕ   rÙ   rÚ   rÜ   rÝ   rß   ra   r*   rá   râ   rã   r`   rS   ræ   r   r   r   r   r·     s6        þ
g]	

r·   c                   @   sj   e Zd Zd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d„ Zdd„ Zdd„ Zdd„ ZdS )Ú
PTYProcessz<
    An operating-system Process that uses PTY support.
    rz   Nc
              
   C   s  t dkrt|	ttfƒstdƒ‚tj | |¡ t | |¡ t|	ttfƒrR|	\}
}}nt  	¡ \}
}z| j
|||||||
|d W n0   t|	ttfƒs¦t |
¡ t |¡ ‚ Y nX t |¡ t |
¡ |
| _|  ¡  d| _d| _z| j | ¡ W n   t ¡  Y nX t| j| ƒ dS )r¸   Nz:cannot use PTYProcess on platforms without the pty module.)ÚmasterfdÚslavefdr1   rz   )Úptyr×   Útupler   r—   r   r2   r3   rb   Úopenptyr–   r   r,   r   r4   r7   r@   rZ   r%   rÂ   rÅ   r   r"   r&   r$   )rA   rB   r‘   r’   r“   rŽ   rÂ   r   r   ZusePTYré   rê   Ú_r   r   r   r3   è  s<    ÿ ÿ




zPTYProcess.__init__c                 C   s¢   t  |¡ t  ¡  t |tjd¡ tdƒD ]}||kr*t  |¡ q*t  |d¡ t  |d¡ t  |d¡ t	ƒ D ](}|dkrlzt  |¡ W ql   Y qlX ql|  
¡  dS )a9  
        Set up child process after C{fork()} but before C{exec()}.

        This involves:

            - closing C{masterfd}, since it is not used in the subprocess

            - creating a new session with C{os.setsid}

            - changing the controlling terminal of the process (and the new
              session) to point at C{slavefd}

            - duplicating C{slavefd} to standard input, output, and error

            - closing all other open file descriptors (according to
              L{_listOpenFDs})

            - re-setting all signal handlers to C{SIG_DFL}

        @param masterfd: The master end of a PTY file descriptors opened with
            C{openpty}.
        @type masterfd: L{int}

        @param slavefd: The slave end of a PTY opened with C{openpty}.
        @type slavefd: L{int}
        Ú ry   r   r1   rt   N)r   r,   ÚsetsidÚfcntlZioctlÚtermiosZ	TIOCSCTTYr   rÏ   r¦   rs   )rA   ré   rê   r7   r   r   r   r‚     s     

zPTYProcess._setupChildc                 C   s   d S rL   r   rE   r   r   r   rÜ   J  s    zPTYProcess.closeStdinc                 C   s   d S rL   r   rE   r   r   r   rÝ   P  s    zPTYProcess.closeStdoutc                 C   s   d S rL   r   rE   r   r   r   rß   T  s    zPTYProcess.closeStderrc                    s   t  ˆ j‡ fdd„¡S )zM
        Called when my standard output stream is ready for reading.
        c                    s   ˆ j  d| ¡S rn   rå   )rI   rE   r   r   Ú<lambda>^  r\   z#PTYProcess.doRead.<locals>.<lambda>)r   r^   r7   rE   r   rE   r   rQ   X  s    
þzPTYProcess.doReadc                 C   s   | j S )zR
        This returns the file number of standard output on this process.
        rD   rE   r   r   r   r;   a  s    zPTYProcess.filenoc                 C   s   | j dkrt | ¡ d S rÞ   )rç   rb   ræ   rE   r   r   r   ræ   h  s    
z PTYProcess.maybeCallProcessEndedc                 C   s4   t j | |¡ t | j¡ |  jd7  _|  ¡  dS )zU
        I call this to clean up when one or all of my connections has died.
        r1   N)r   r2   rR   r   r,   r7   rç   ræ   rT   r   r   r   rR   s  s    zPTYProcess.connectionLostc                 C   s   t  | j|¡S rF   )r   rG   r7   rN   r   r   r   rK   }  s    zPTYProcess.writeSomeData)NNN)rV   rW   rX   rY   r%   r$   r3   r‚   rÜ   rÝ   rß   rQ   r;   ræ   rR   rK   r   r   r   r   rè   ß  s         ÿ
11	
rè   )<rY   Z
__future__r   r   r   Ztwisted.python.runtimer   Z	isWindowsr³   rc   r{   r   rˆ   r+   rj   r8   r€   rŠ   rë   rñ   rò   Zzope.interfacer   Ztwisted.pythonr   r   Ztwisted.python.utilr	   Ztwisted.python.compatr
   r   r   Ztwisted.internetr   r   r   Ztwisted.internet.mainr   r   Ztwisted.internet._baseprocessr   Ztwisted.internet.interfacesr   rk   r   r   r&   r'   r/   rO   r2   r0   r[   Úobjectrb   r    r¶   r¦   r·   rè   r   r   r   r   Ú<module>   sb   

wA \m	  Q