U
    c6{i×.  ã                   @   s¾   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZmZmZmZ G d	d
„ d
eje
je ƒZG dd„ dejƒZG dd„ deƒZG dd„ dejejƒZdS )zH
I hold resource classes and helper classes that deal with CGI scripts.
é    N)ÚAnyStr)Úprotocol)ÚLogger)Úfilepath)Úpb)ÚhttpÚresourceÚserverÚstaticc                   @   s$   e Zd Zdd„ Zdd„ Zdd„ ZdS )ÚCGIDirectoryc                 C   s   t j | ¡ tj | |¡ d S ©N)r   ÚResourceÚ__init__r   ÚFilePath)ÚselfÚpathname© r   ú5/tmp/pip-unpacked-wheel-hfbvu0bz/twisted/web/twcgi.pyr      s    zCGIDirectory.__init__c                 C   s:   |   |¡}| ¡ stjjS | ¡ r,t|jƒS t|jƒS d S r   )	ÚchildÚexistsr
   ZFileZchildNotFoundÚisdirr   ÚpathÚ	CGIScript)r   r   ÚrequestZfnpr   r   r   ÚgetChild   s    

zCGIDirectory.getChildc                 C   s   t  d¡}| |¡S )Nz1CGI directories do not support directory listing.)r   Z
NoResourceÚrender)r   r   ZnotFoundr   r   r   r   %   s    ÿzCGIDirectory.renderN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   r   r   r      s   	r   c                   @   s2   e Zd ZdZdZd
dd„Zdd„ Zg fdd	„ZdS )r   zö
    L{CGIScript} is a resource which runs child processes according to the CGI
    specification.

    The implementation is complex due to the fact that it requires asynchronous
    IPC with an external process with an unpleasant protocol.
    é   Nc                 C   s$   || _ |dkrddlm} || _dS )zA
        Initialize, with the name of a CGI script file.
        Nr   )Úreactor)ÚfilenameÚtwisted.internetr    Ú_reactor)r   r!   Úregistryr    r   r   r   r   7   s    zCGIScript.__init__c              
   C   s®  dd  |j¡ }| ¡  d¡d }tj|d|jt| ¡ j	ƒ|j
|| j|jdœ	}| ¡ j}|dk	rh||d< |j}|r„dd  |¡ |d	< t|d
ƒrÀ|j dd¡ |j ¡ }|j dd¡ t|ƒ|d< z|j d¡}W n  tk
rð   d|d< g }	Y n@X |j|d d…  }
|d< d|
k�rg }	ndd„ |
 d¡D ƒ}	| ¡  ¡ D ]4\}}| dd¡ ¡ }|dk�rfd| }|||< �q<tj ¡ D ]\}}||k�r||||< �q||  |||	¡ tjS )a  
        Do various things to conform to the CGI specification.

        I will set up the usual slew of environment variables, then spin off a
        process.

        @type request: L{twisted.web.http.Request}
        @param request: An HTTP request.
        ó   /ó   :r   zCGI/1.1)	ÚSERVER_SOFTWAREZSERVER_NAMEZGATEWAY_INTERFACEZSERVER_PROTOCOLZSERVER_PORTÚREQUEST_METHODZSCRIPT_NAMEZSCRIPT_FILENAMEZREQUEST_URINZREMOTE_ADDRú/Z	PATH_INFOÚcontenté   ÚCONTENT_LENGTHó   ?Ú ÚQUERY_STRINGr   ó   =c                 S   s   g | ]}t j | ¡ ¡‘qS r   )ÚurllibÚparseÚunquoteÚdecode)Ú.0Úxr   r   r   Ú
<listcomp>t   s     z$CGIScript.render.<locals>.<listcomp>ó   +ó   -ó   _)s   content-types   content-lengths   proxys   HTTP_)ÚjoinZprepathZgetRequestHostnameÚsplitr	   ÚversionZclientprotoÚstrZgetHostÚportÚmethodr!   ÚuriZgetClientAddressÚhostZpostpathÚhasattrr*   ÚseekÚtellÚindexÚ
ValueErrorZgetAllHeadersÚitemsÚreplaceÚupperÚosÚenvironÚ
runProcessZNOT_DONE_YET)r   r   Z
scriptNameZ
serverNameÚenvÚipÚppÚlengthZqindexÚqargsÚqsÚtitleÚheaderÚenvnameÚkeyÚvaluer   r   r   r   C   sT    
÷






zCGIScript.renderc              	   C   s4   t |ƒ}| j || j| jg| |tj | j¡¡ dS )aI  
        Run the cgi script.

        @type env: A L{dict} of L{str}, or L{None}
        @param env: The environment variables to pass to the process that will
            get spawned. See
            L{twisted.internet.interfaces.IReactorProcess.spawnProcess} for
            more information about environments and process creation.

        @type request: L{twisted.web.http.Request}
        @param request: An HTTP request.

        @type qargs: A L{list} of L{str}
        @param qargs: The command line arguments to pass to the process that
            will get spawned.
        N)ÚCGIProcessProtocolr#   ÚspawnProcessr!   rK   r   Údirname©r   rN   r   rR   Úpr   r   r   rM   „   s    
ûzCGIScript.runProcess)NN)r   r   r   Ú__doc__ZisLeafr   r   rM   r   r   r   r   r   ,   s
   
Ar   c                   @   s    e Zd ZdZdZg fdd„ZdS )ÚFilteredScripta  
    I am a special version of a CGI script, that uses a specific executable.

    This is useful for interfacing with other scripting languages that adhere
    to the CGI standard. My C{filter} attribute specifies what executable to
    run, and my C{filename} init parameter describes which script to pass to
    the first argument of that script.

    To customize me for a particular location of a CGI interpreter, override
    C{filter}.

    @type filter: L{str}
    @ivar filter: The absolute path to the executable.
    z/usr/bin/catc              	   C   s8   t |ƒ}| j || j| j| jg| |tj | j¡¡ dS )ad  
        Run a script through the C{filter} executable.

        @type env: A L{dict} of L{str}, or L{None}
        @param env: The environment variables to pass to the process that will
            get spawned. See
            L{twisted.internet.interfaces.IReactorProcess.spawnProcess}
            for more information about environments and process creation.

        @type request: L{twisted.web.http.Request}
        @param request: An HTTP request.

        @type qargs: A L{list} of L{str}
        @param qargs: The command line arguments to pass to the process that
            will get spawned.
        N)rY   r#   rZ   Úfilterr!   rK   r   r[   r\   r   r   r   rM   ±   s    ûzFilteredScript.runProcessN)r   r   r   r^   r`   rM   r   r   r   r   r_   Ÿ   s   r_   c                   @   s†   e Zd ZdZdZdZdZeƒ 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d„ Zdd„ Zdd„ Zdd„ ZdS )rY   r   r   ó    Fc                 C   s   |   ¡  d S r   )ÚresumeProducing©r   Zissuerr   r   r   Úview_resumeProducingÖ   s    z'CGIProcessProtocol.view_resumeProducingc                 C   s   |   ¡  d S r   )ÚpauseProducingrc   r   r   r   Úview_pauseProducingÙ   s    z&CGIProcessProtocol.view_pauseProducingc                 C   s   |   ¡  d S r   )ÚstopProducingrc   r   r   r   Úview_stopProducingÜ   s    z%CGIProcessProtocol.view_stopProducingc                 C   s   | j  ¡  d S r   )Ú	transportrb   ©r   r   r   r   rb   ß   s    z"CGIProcessProtocol.resumeProducingc                 C   s   | j  ¡  d S r   )ri   re   rj   r   r   r   re   â   s    z!CGIProcessProtocol.pauseProducingc                 C   s   | j  ¡  d S r   )ri   ZloseConnectionrj   r   r   r   rg   å   s    z CGIProcessProtocol.stopProducingc                 C   s   || _ | j  ¡  | j¡ d S r   )r   ZnotifyFinishZaddBothÚ	_finished)r   r   r   r   r   r   è   s    zCGIProcessProtocol.__init__c                 C   sH   | j  | d¡ | j j dd¡ | j j ¡ }|r:| j |¡ | j ¡  d S )Nr   r   )r   ZregisterProducerr*   rD   Úreadri   ÚwriteZ
closeStdin)r   r*   r   r   r   ÚconnectionMadeì   s    z!CGIProcessProtocol.connectionMadec                 C   s   | j | | _ d S r   )Ú	errortext)r   Úerrorr   r   r   ÚerrReceivedô   s    zCGIProcessProtocol.errReceivedc              	   C   s   | j �rˆ| j| }g }dD ]$}| |¡}|dkr| ||f¡ q|�rzd| j_| ¡  |d \}}|d|… | _|dt|ƒd … }| j |¡}|D ]Ê}| d¡}	|	dkr¼| j	j
d|d� q”|d|	…  ¡ }
||	d d… }|
d	krò| j tj¡ |
d
k�rBzt|dd… ƒ}W n" tk
�r2   | j	 
d¡ Y nX | j |¡ q”|
 ¡ dkr”| jj |
|¡ q”||t|ƒ d… }d| _ | j �rˆ|| _| j �sœ| j |¡ dS )z)
        Handle a chunk of input
        )s   

s   

s   s   

éÿÿÿÿNr   r+   s   : z)ignoring malformed CGI header: {header!r})rU   s   locations   statusé   zmalformed status header)s   servers   date)Úhandling_headersÚ
headertextÚfindÚappendr   ZdefaultContentTypeÚsortÚlenr<   Ú_logrp   ÚlowerZsetResponseCoder   ÚFOUNDÚintÚBaseExceptionZresponseHeadersZaddRawHeaderrm   )r   ÚoutputÚtextZ
headerEndsÚ	delimiterZ	headerendZ	linebreakÚheadersrU   ÚbrZ
headerNameÚ
headerTextZ	statusNumr   r   r   ÚoutReceived÷   sT    


 ÿ
 ÿzCGIProcessProtocol.outReceivedc                 C   s¦   |j jdkr&| jjd| jj|j jd� | jrD| jjd| jj| jd� | jrˆ| jjd| jj| jd� | j	sˆ| j 
t tjdd	¡ | j¡¡ | j	s¢| j ¡  | j ¡  d S )
Nr   z*CGI {uri} exited with exit code {exitCode})rA   ÚexitCodez"Errors from CGI {uri}: {errorText})rA   Z	errorTextz/Premature end of headers in {uri}: {headerText})rA   r„   zCGI Script Errorz Premature end of script headers.)rX   r†   rz   rp   r   rA   ro   rt   ru   Ú_requestFinishedrm   r   Z	ErrorPager   ÚINTERNAL_SERVER_ERRORr   ZunregisterProducerÚfinish)r   Úreasonr   r   r   ÚprocessEnded1  s>    ýýýýüÿ
zCGIProcessProtocol.processEndedc                 C   s
   d| _ dS )zc
        Record the end of the response generation for the request being
        serviced.
        TN)r‡   )r   Zignoredr   r   r   rk   R  s    zCGIProcessProtocol._finishedN)r   r   r   rt   Zheaders_writtenru   ro   r   rz   r‡   rd   rf   rh   rb   re   rg   r   rn   rq   r…   r‹   rk   r   r   r   r   rY   Ì   s$   :!rY   )r^   rK   r1   Útypingr   r"   r   Ztwisted.loggerr   Ztwisted.pythonr   Ztwisted.spreadr   Ztwisted.webr   r   r	   r
   r   r   r   r   r_   ZProcessProtocolZViewablerY   r   r   r   r   Ú<module>   s   s-