o
    ¯bµ.  ã                   @   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mZmZmZ G dd	„ d	ejejƒ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)Ú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   ú3/usr/lib/python3/dist-packages/twisted/web/twcgi.pyr      s   zCGIDirectory.__init__c                 C   s6   |   |¡}| ¡ stjjS | ¡ rt|jƒS t|jƒS r   )	ÚchildÚexistsr	   ÚFileÚchildNotFoundÚisdirr
   ÚpathÚ	CGIScript)r   r   ÚrequestÚfnpr   r   r   ÚgetChild   s   


zCGIDirectory.getChildc                 C   s   t  d¡}| |¡S )Nz1CGI directories do not support directory listing.)r   Ú
NoResourceÚrender)r   r   Ú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u 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   6   s   
zCGIScript.__init__c              
   C   s¢  dd  |j¡ }| ¡  d¡d }tj|d|jt| ¡ j	ƒ|j
|| j|jdœ	}| ¡ j}|dur4||d< |j}|rBdd  |¡ |d	< t|d
ƒr`|j dd¡ |j ¡ }|j dd¡ t|ƒ|d< z|j d¡}W n tyw   d|d< g }	Y nw |j|d d…  }
|d< d|
v rŒg }	n
dd„ |
 d¡D ƒ}	| ¡  ¡ D ]\}}| dd¡ ¡ }|dvr°d| }|||< qœtj ¡ D ]\}}||v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_SOFTWAREÚSERVER_NAMEÚGATEWAY_INTERFACEÚSERVER_PROTOCOLÚSERVER_PORTÚREQUEST_METHODÚSCRIPT_NAMEÚSCRIPT_FILENAMEÚREQUEST_URINÚREMOTE_ADDRú/Ú	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>s   s    z$CGIScript.render.<locals>.<listcomp>ó   +ó   -ó   _)s   content-types   content-lengths   proxys   HTTP_)ÚjoinÚprepathÚgetRequestHostnameÚsplitr   ÚversionÚclientprotoÚstrÚgetHostÚportÚmethodr%   ÚuriÚgetClientAddressÚhostÚpostpathÚhasattrr7   ÚseekÚtellÚindexÚ
ValueErrorÚgetAllHeadersÚitemsÚreplaceÚupperÚosÚenvironÚ
runProcessÚNOT_DONE_YET)r   r   Ú
scriptNameÚ
serverNameÚenvÚipÚppÚlengthÚqindexÚqargsÚqsÚtitleÚheaderÚenvnameÚkeyÚvaluer   r   r   r   B   sX   
÷


þ
€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%   r_   r   Údirname©r   re   r   rj   Úpr   r   r   ra   ƒ   s   
ûzCGIScript.runProcess)NN)r    r!   r"   Ú__doc__ÚisLeafr   r   ra   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)rq   r'   rr   Úfilterr%   r_   r   rs   rt   r   r   r   ra   °   s   ûzFilteredScript.runProcessN)r    r!   r"   rv   ry   ra   r   r   r   r   rx   ž   s    rx   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 )rq   r#   r   ó    Fc                 C   ó   |   ¡  d S r   )ÚresumeProducing©r   Úissuerr   r   r   Úview_resumeProducingÕ   ó   z'CGIProcessProtocol.view_resumeProducingc                 C   r{   r   )ÚpauseProducingr}   r   r   r   Úview_pauseProducingØ   r€   z&CGIProcessProtocol.view_pauseProducingc                 C   r{   r   )ÚstopProducingr}   r   r   r   Úview_stopProducingÛ   r€   z%CGIProcessProtocol.view_stopProducingc                 C   ó   | j  ¡  d S r   )Ú	transportr|   ©r   r   r   r   r|   Þ   ó   z"CGIProcessProtocol.resumeProducingc                 C   r…   r   )r†   r�   r‡   r   r   r   r�   á   rˆ   z!CGIProcessProtocol.pauseProducingc                 C   r…   r   )r†   ÚloseConnectionr‡   r   r   r   rƒ   ä   rˆ   z CGIProcessProtocol.stopProducingc                 C   s   || _ | j  ¡  | j¡ d S r   )r   ÚnotifyFinishÚ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   ÚregisterProducerr7   rW   Úreadr†   ÚwriteÚ
closeStdin)r   r7   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|r¸d| j_| ¡  |d \}}|d|… | _|dt|ƒd … }| j |¡}|D ]b}| d¡}	|	dkr\| j	j
d|d� qH|d|	…  ¡ }
||	d d… }|
d	krw| j tj¡ |
d
krœz
t|dd… ƒ}W n ty”   | j	 
d¡ Y qHw | j |¡ qH|
 ¡ dvrª| jj |
|¡ qH||t|ƒ d… }d| _ | j r¾|| _| j sÉ| j |¡ dS dS )z)
        Handle a chunk of input
        )s   

s   

s   s   

éÿÿÿÿNr   r8   s   : z)ignoring malformed CGI header: {header!r})rm   s   locations   statusé   zmalformed status header)s   servers   date)Úhandling_headersÚ
headertextÚfindÚappendr   ÚdefaultContentTypeÚsortÚlenrK   Ú_logr“   ÚlowerÚsetResponseCoder   ÚFOUNDÚintÚBaseExceptionÚresponseHeadersÚaddRawHeaderr�   )r   ÚoutputÚtextÚ
headerEndsÚ	delimiterÚ	headerendÚ	linebreakÚheadersrm   ÚbrÚ
headerNameÚ
headerTextÚ	statusNumr   r   r   ÚoutReceivedö   sX   

€
ÿÿÿ€ÿzCGIProcessProtocol.outReceivedc                 C   sª   |j jdkr| jjd| jj|j jd� | jr"| jjd| jj| jd� | jrD| jjd| jj| jd� | j	sD| j 
t tjdd	¡ | j¡¡ | j	sS| j ¡  | j ¡  d S d S )
Nr   z*CGI {uri} exited with exit code {exitCode})rR   ÚexitCodez"Errors from CGI {uri}: {errorText})rR   Ú	errorTextz/Premature end of headers in {uri}: {headerText})rR   r¯   zCGI Script Errorz Premature end of script headers.)rp   r²   rž   r“   r   rR   r’   r—   r˜   Ú_requestFinishedr�   r   Ú	ErrorPager   ÚINTERNAL_SERVER_ERRORr   ÚunregisterProducerÚfinish)r   Úreasonr   r   r   ÚprocessEnded0  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   Úignoredr   r   r   rŒ   Q  s   
zCGIProcessProtocol._finishedN)r    r!   r"   r—   Úheaders_writtenr˜   r’   r   rž   r´   r   r‚   r„   r|   r�   rƒ   r   r‘   r”   r±   rº   rŒ   r   r   r   r   rq   Ë   s&    :!rq   )rv   r_   r>   r&   r   Útwisted.loggerr   Útwisted.pythonr   Útwisted.spreadr   Útwisted.webr   r   r   r	   r   r   r
   r   rx   ÚProcessProtocolÚViewablerq   r   r   r   r   Ú<module>   s   s-