U
    ad                     @   s  d Z dZdddddg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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dd	lmZ dd
l	mZ dZdZG dd dejZG dd dejeZG dd dej Z!G dd de!Z"dd Z#da$dd Z%dd Z&G dd de"Z'dd Z(e!edddfddZ)e*dkrddl+Z+e+, Z-e-j.dd d!d" e-j.d#d$d%d&d' e-j.d(d)e/ d*d+ e-j.d,d-de0d.d/d0 e-1 Z2e2j3re'Z4nee"e2j5d1Z4G d2d3 d3eZ6e)e4e6e2j7e2j8d4 dS )5a@  HTTP server classes.

Note: BaseHTTPRequestHandler doesn't implement any HTTP request; see
SimpleHTTPRequestHandler for simple implementations of GET, HEAD and POST,
and CGIHTTPRequestHandler for CGI scripts.

It does, however, optionally implement HTTP/1.1 persistent connections,
as of version 0.3.

Notes on CGIHTTPRequestHandler
------------------------------

This class implements GET and POST requests to cgi-bin scripts.

If the os.fork() function is not present (e.g. on Windows),
subprocess.Popen() is used as a fallback, with slightly altered semantics.

In all cases, the implementation is intentionally naive -- all
requests are executed synchronously.

SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL
-- it may execute arbitrary Python code or external programs.

Note that status code 200 is sent prior to execution of a CGI script, so
scripts cannot send other status codes such as 302 (redirect).

XXX To do:

- log requests even later (to capture byte count)
- log user-agent header and other interesting goodies
- send error log to separate file
z0.6
HTTPServerThreadingHTTPServerBaseHTTPRequestHandlerSimpleHTTPRequestHandlerCGIHTTPRequestHandler    N)partial)
HTTPStatusa  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <title>Error response</title>
    </head>
    <body>
        <h1>Error response</h1>
        <p>Error code: %(code)d</p>
        <p>Message: %(message)s.</p>
        <p>Error code explanation: %(code)s - %(explain)s.</p>
    </body>
</html>
ztext/html;charset=utf-8c                   @   s   e Zd ZdZdd ZdS )r      c                 C   s4   t j|  | jdd \}}t|| _|| _dS )z.Override server_bind to store the server name.N   )socketserver	TCPServerserver_bindZserver_addresssocketZgetfqdnserver_nameserver_port)selfhostport r   !/usr/lib/python3.8/http/server.pyr      s    zHTTPServer.server_bindN)__name__
__module____qualname__Zallow_reuse_addressr   r   r   r   r   r      s   c                   @   s   e Zd ZdZdS )r   TN)r   r   r   Zdaemon_threadsr   r   r   r   r      s   c                   @   s  e Zd ZdZdej d  Zde Z	e
ZeZdZdd Zdd	 Zd
d Zdd Zd@ddZdAddZdBddZdd Zdd Zdd ZdCddZdd Zd d! Zd"d# ZdDd$d%Zd&d' Zd(d)d*d+d,d-d.gZdd/d0d1d2d3d4d5d6d7d8d9d:gZ d;d< Z!d=Z"e#j$j%Z&d>d? e'j() D Z*dS )Er   a  HTTP request handler base class.

    The following explanation of HTTP serves to guide you through the
    code as well as to expose any misunderstandings I may have about
    HTTP (so you don't need to read the code to figure out I'm wrong
    :-).

    HTTP (HyperText Transfer Protocol) is an extensible protocol on
    top of a reliable stream transport (e.g. TCP/IP).  The protocol
    recognizes three parts to a request:

    1. One line identifying the request type and path
    2. An optional set of RFC-822-style headers
    3. An optional data part

    The headers and data are separated by a blank line.

    The first line of the request has the form

    <command> <path> <version>

    where <command> is a (case-sensitive) keyword such as GET or POST,
    <path> is a string containing path information for the request,
    and <version> should be the string "HTTP/1.0" or "HTTP/1.1".
    <path> is encoded using the URL encoding scheme (using %xx to signify
    the ASCII character with hex code xx).

    The specification specifies that lines are separated by CRLF but
    for compatibility with the widest range of clients recommends
    servers also handle LF.  Similarly, whitespace in the request line
    is treated sensibly (allowing multiple spaces between components
    and allowing trailing whitespace).

    Similarly, for output, lines ought to be separated by CRLF pairs
    but most clients grok LF characters just fine.

    If the first line of the request has the form

    <command> <path>

    (i.e. <version> is left out) then this is assumed to be an HTTP
    0.9 request; this form has no optional headers and data part and
    the reply consists of just the data.

    The reply form of the HTTP 1.x protocol again has three parts:

    1. One line giving the response code
    2. An optional set of RFC-822-style headers
    3. The data

    Again, the headers and data are separated by a blank line.

    The response code line has the form

    <version> <responsecode> <responsestring>

    where <version> is the protocol version ("HTTP/1.0" or "HTTP/1.1"),
    <responsecode> is a 3-digit response code indicating success or
    failure of the request, and <responsestring> is an optional
    human-readable string explaining what the response code means.

    This server parses the request and the headers, and then calls a
    function specific to the request type (<command>).  Specifically,
    a request SPAM will be handled by a method do_SPAM().  If no
    such method exists the server sends an error response to the
    client.  If it exists, it is called with no arguments:

    do_SPAM()

    Note that the request name is case sensitive (i.e. SPAM and spam
    are different requests).

    The various request details are stored in instance variables:

    - client_address is the client IP address in the form (host,
    port);

    - command, path and version are the broken-down request line;

    - headers is an instance of email.message.Message (or a derived
    class) containing the header information;

    - rfile is a file object open for reading positioned at the
    start of the optional input data part;

    - wfile is a file object open for writing.

    IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING!

    The first thing to be written must be the response line.  Then
    follow 0 or more header lines, then a blank line, and then the
    actual data (if any).  The meaning of the header lines depends on
    the command executed by the server; in most cases, when data is
    returned, there should be at least one header line of the form

    Content-type: <type>/<subtype>

    where <type> and <subtype> should be registered MIME types,
    e.g. "text/html" or "text/plain".

    zPython/r   z	BaseHTTP/HTTP/0.9c              
   C   s  d| _ | j | _}d| _t| jd}|d}|| _| }t	|dkrLdS t	|dkr&|d }zT|
d	srt|d
dd }|d}t	|dkrtt|d t|d f}W n, ttfk
r   | tjd|  Y dS X |dkr | jdkr d| _|dkr | tjd|  dS || _dt	|  krBdksZn | tjd|  dS |dd \}}t	|dkrd| _|dkr| tjd|  dS || | _ | _ztjj| j| jd| _W n tjjk
r } z| tjdt| W Y dS d}~X Y nB tjjk
rH } z| tjdt| W Y dS d}~X Y nX | jdd}	|	 dkrnd| _n |	 dkr| jdkrd| _| jdd}
|
 dkr| jdkr| jdkr|  sdS dS )aH  Parse a request (internal).

        The request should be stored in self.raw_requestline; the results
        are in self.command, self.path, self.request_version and
        self.headers.

        Return True for success, False for failure; on failure, any relevant
        error response has already been sent back.

        NTz
iso-8859-1z
r   F   zHTTP//r	   .r
   zBad request version (%r))r	   r	   zHTTP/1.1)r
   r   zInvalid HTTP version (%s)zBad request syntax (%r)ZGETzBad HTTP/0.9 request type (%r))Z_classzLine too longzToo many headers
Connection close
keep-aliveZExpectz100-continue) commanddefault_request_versionrequest_versionclose_connectionstrraw_requestlinerstriprequestlinesplitlen
startswith
ValueErrorint
IndexError
send_errorr   ZBAD_REQUESTprotocol_versionZHTTP_VERSION_NOT_SUPPORTEDpathhttpclientZparse_headersrfileMessageClassheadersZLineTooLongZREQUEST_HEADER_FIELDS_TOO_LARGEZHTTPExceptiongetlowerhandle_expect_100)r   versionr)   wordsZbase_version_numberZversion_numberr"   r2   errZconntypeZexpectr   r   r   parse_request  s    






z$BaseHTTPRequestHandler.parse_requestc                 C   s   |  tj |   dS )a7  Decide what to do with an "Expect: 100-continue" header.

        If the client is expecting a 100 Continue response, we must
        respond with either a 100 Continue or a final response before
        waiting for the request body. The default is to always respond
        with a 100 Continue. You can behave differently (for example,
        reject unauthorized requests) by overriding this method.

        This method should either return True (possibly after sending
        a 100 Continue response) or send an error response and return
        False.

        T)send_response_onlyr   ZCONTINUEend_headersr   r   r   r   r:   p  s    z(BaseHTTPRequestHandler.handle_expect_100c              
   C   s   z| j d| _t| jdkrBd| _d| _d| _| tj	 W dS | jsTd| _
W dS |  sbW dS d| j }t| |s| tjd| j  W dS t| |}|  | j  W n< tjk
r } z| d| d| _
W Y dS d}~X Y nX dS )	zHandle a single HTTP request.

        You normally don't need to override this method; see the class
        __doc__ string for information on how to handle specific HTTP
        commands such as GET and POST.

        i  i   r   NTZdo_zUnsupported method (%r)zRequest timed out: %r)r5   readliner'   r+   r)   r$   r"   r0   r   ZREQUEST_URI_TOO_LONGr%   r>   hasattrNOT_IMPLEMENTEDgetattrwfileflushr   Ztimeout	log_error)r   Zmnamemethoder   r   r   handle_one_request  s6    


z)BaseHTTPRequestHandler.handle_one_requestc                 C   s"   d| _ |   | j s|   qdS )z&Handle multiple requests if necessary.TN)r%   rK   rA   r   r   r   handle  s    zBaseHTTPRequestHandler.handleNc                 C   s  z| j | \}}W n tk
r.   d\}}Y nX |dkr<|}|dkrH|}| d|| | || | dd d}|dkr|tjtjtjfkr| j	|t
j|ddt
j|ddd	 }|d
d}| d| j | dtt| |   | jdkr|r| j| dS )ak  Send and log an error reply.

        Arguments are
        * code:    an HTTP error code
                   3 digits
        * message: a simple optional 1 line reason phrase.
                   *( HTAB / SP / VCHAR / %x80-FF )
                   defaults to short entry matching the response code
        * explain: a detailed message defaults to the long entry
                   matching the response code.

        This sends an error response (so it must be called before any
        output has been generated), logs the error, and finally sends
        a piece of HTML explaining the error to the user.

        )???rM   Nzcode %d, message %sr   r       Fquote)codemessageexplainzUTF-8replacezContent-TypeContent-LengthZHEAD)	responsesKeyErrorrH   send_responsesend_headerr   Z
NO_CONTENTZRESET_CONTENTNOT_MODIFIEDerror_message_formathtmlescapeencodeerror_content_typer&   r+   r@   r"   rF   write)r   rQ   rR   rS   ZshortmsgZlongmsgZbodyZcontentr   r   r   r0     s:    z!BaseHTTPRequestHandler.send_errorc                 C   s:   |  | | || | d|   | d|   dS )zAdd the response header to the headers buffer and log the
        response code.

        Also send two standard headers with the server software
        version and the current date.

        ZServerZDateN)log_requestr?   rY   version_stringdate_time_stringr   rQ   rR   r   r   r   rX     s    
z$BaseHTTPRequestHandler.send_responsec                 C   sd   | j dkr`|dkr0|| jkr,| j| d }nd}t| ds@g | _| jd| j||f dd dS )	zSend the response header only.r   Nr   r   _headers_bufferz
%s %d %s
latin-1strict)r$   rV   rC   re   appendr1   r^   rd   r   r   r   r?     s    



 z)BaseHTTPRequestHandler.send_response_onlyc                 C   sl   | j dkr6t| dsg | _| jd||f dd | dkrh| dkrVd| _n| d	krhd
| _dS )z)Send a MIME header to the headers buffer.r   re   z%s: %s
rf   rg   Z
connectionr    Tr!   FN)r$   rC   re   rh   r^   r9   r%   )r   keywordvaluer   r   r   rY     s    

z"BaseHTTPRequestHandler.send_headerc                 C   s"   | j dkr| jd |   dS )z,Send the blank line ending the MIME headers.r   s   
N)r$   re   rh   flush_headersrA   r   r   r   r@     s    
z"BaseHTTPRequestHandler.end_headersc                 C   s(   t | dr$| jd| j g | _d S )Nre       )rC   rF   r`   joinre   rA   r   r   r   rk     s    
z$BaseHTTPRequestHandler.flush_headers-c                 C   s.   t |tr|j}| d| jt|t| dS )zNLog an accepted request.

        This is called by send_response().

        z
"%s" %s %sN)
isinstancer   rj   log_messager)   r&   )r   rQ   sizer   r   r   ra     s    
  z"BaseHTTPRequestHandler.log_requestc                 G   s   | j |f|  dS )zLog an error.

        This is called when a request cannot be fulfilled.  By
        default it passes the message on to log_message().

        Arguments are the same as for log_message().

        XXX This should go to the separate error log.

        N)rp   r   formatargsr   r   r   rH   #  s    z BaseHTTPRequestHandler.log_errorc                 G   s&   t jd|  |  || f  dS )a  Log an arbitrary message.

        This is used by all other logging functions.  Override
        it if you have specific logging wishes.

        The first argument, FORMAT, is a format string for the
        message to be logged.  If the format string contains
        any % escapes requiring parameters, they should be
        specified as subsequent arguments (it's just like
        printf!).

        The client ip and current date/time are prefixed to
        every message.

        z%s - - [%s] %s
N)sysstderrr`   address_stringlog_date_time_stringrr   r   r   r   rp   1  s    z"BaseHTTPRequestHandler.log_messagec                 C   s   | j d | j S )z*Return the server software version string. )server_versionsys_versionrA   r   r   r   rb   G  s    z%BaseHTTPRequestHandler.version_stringc                 C   s    |dkrt   }tjj|ddS )z@Return the current date and time formatted for a message header.NT)Zusegmt)timeemailutilsZ
formatdate)r   Z	timestampr   r   r   rc   K  s    z'BaseHTTPRequestHandler.date_time_stringc              	   C   sB   t   }t |\	}}}}}}}}	}
d|| j| ||||f }|S )z.Return the current time formatted for logging.z%02d/%3s/%04d %02d:%02d:%02d)r|   	localtime	monthname)r   ZnowZyearZmonthZdayZhhZmmZssxyzsr   r   r   rx   Q  s         z+BaseHTTPRequestHandler.log_date_time_stringZMonZTueZWedZThuZFriZSatZSunZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDecc                 C   s
   | j d S )zReturn the client address.r   )client_addressrA   r   r   r   rw   _  s    z%BaseHTTPRequestHandler.address_stringHTTP/1.0c                 C   s   i | ]}||j |jfqS r   )phraseZdescription).0vr   r   r   
<dictcomp>n  s    z!BaseHTTPRequestHandler.<dictcomp>)NN)N)N)rn   rn   )N)+r   r   r   __doc__ru   r;   r*   r{   __version__rz   DEFAULT_ERROR_MESSAGEr[   DEFAULT_ERROR_CONTENT_TYPEr_   r#   r>   r:   rK   rL   r0   rX   r?   rY   r@   rk   ra   rH   rp   rb   rc   rx   Zweekdaynamer   rw   r1   r3   r4   ZHTTPMessager6   r   __members__valuesrV   r   r   r   r   r      sV   gc%
5



          	c                       s   e Zd ZdZde Zdd fdd
Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Zejsle  ej Zeddddd   ZS )r   aW  Simple HTTP request handler with GET and HEAD commands.

    This serves files from the current directory and any of its
    subdirectories.  The MIME type for files is determined by
    calling the .guess_type() method.

    The GET and HEAD requests are identical except that the HEAD
    request omits the actual contents of the file.

    zSimpleHTTP/N	directoryc                   s(   |d krt  }|| _t j|| d S N)osgetcwdr   super__init__)r   r   rt   kwargs	__class__r   r   r     s    z!SimpleHTTPRequestHandler.__init__c                 C   s.   |   }|r*z| || j W 5 |  X dS )zServe a GET request.N)	send_headr    copyfilerF   r   fr   r   r   do_GET  s
    zSimpleHTTPRequestHandler.do_GETc                 C   s   |   }|r|  dS )zServe a HEAD request.N)r   r    r   r   r   r   do_HEAD  s    z SimpleHTTPRequestHandler.do_HEADc                 C   s^  |  | j}d}tj|rtj| j}|jds| t	j
 |d |d |d d |d |d f}tj|}| d| |   dS d	D ]&}tj||}tj|r|} qq| |S | |}|dr| t	jd
 dS zt|d}W n& tk
r   | t	jd
 Y dS X z"t| }d| jkrd| jkrztj| jd }	W n ttttfk
r|   Y nzX |	j dkr|	j!t"j#j$d}	|	j t"j#j$krt"j"%|j&t"j#j$}
|
j!dd}
|
|	kr| t	j' |   |(  W dS | t	j) | d| | dt*|d  | d| +|j& |   |W S    |(   Y nX dS )a{  Common code for GET and HEAD commands.

        This sends the response code and MIME headers.

        Return value is either a file object (which has to be copied
        to the outputfile by the caller unless the command was HEAD,
        and must be closed by the caller under all circumstances), or
        None, in which case the caller has nothing further to do.

        Nr   r   r	   r
   r      ZLocation)z
index.htmlz	index.htmzFile not foundrbzIf-Modified-SincezIf-None-Match)tzinfo)ZmicrosecondContent-typerU      zLast-Modified),translate_pathr2   r   isdirurllibparseZurlsplitendswithrX   r   ZMOVED_PERMANENTLYZ
urlunsplitrY   r@   rm   existslist_directory
guess_typer0   	NOT_FOUNDopenOSErrorfstatfilenor7   r}   r~   Zparsedate_to_datetime	TypeErrorr/   OverflowErrorr-   r   rT   datetimetimezoneZutcZfromtimestampst_mtimerZ   r    OKr&   rc   )r   r2   r   partsZ	new_partsZnew_urlindexZctypeZfsZimsZ
last_modifr   r   r   r     s     


 

z"SimpleHTTPRequestHandler.send_headc              	   C   s  zt |}W n$ tk
r2   | tjd Y dS X |jdd d g }ztjj	| j
dd}W n  tk
r~   tj	|}Y nX tj|dd	}t }d
| }|d |d |d|  |d|  |d|  |d |D ]v}t j
||}| }	}
t j
|r"|d }	|d }
t j
|r8|d }	|dtjj|
ddtj|	dd	f  q|d d||d}t }|| |d | tj | dd|  | dtt| |   |S )zHelper to produce a directory listing (absent index.html).

        Return value is either a file object, or None (indicating an
        error).  In either case, the headers are sent, making the
        interface the same as for send_head().

        zNo permission to list directoryNc                 S   s   |   S r   )r9   )ar   r   r   <lambda>  rl   z9SimpleHTTPRequestHandler.list_directory.<locals>.<lambda>)keysurrogatepasserrorsFrO   zDirectory listing for %szZ<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">z<html>
<head>z@<meta http-equiv="Content-Type" content="text/html; charset=%s">z<title>%s</title>
</head>z<body>
<h1>%s</h1>z	<hr>
<ul>r   @z<li><a href="%s">%s</a></li>z</ul>
<hr>
</body>
</html>

surrogateescaper   r   ztext/html; charset=%srU   ) r   listdirr   r0   r   r   sortr   r   unquoter2   UnicodeDecodeErrorr\   r]   ru   getfilesystemencodingrh   rm   r   islinkrP   r^   ioBytesIOr`   seekrX   r   rY   r&   r+   r@   )r   r2   listrZdisplaypathenctitlenamefullnameZdisplaynameZlinknameZencodedr   r   r   r   r     sh    







z'SimpleHTTPRequestHandler.list_directoryc                 C   s   | ddd }| ddd }| d}ztjj|dd}W n  tk
rb   tj|}Y nX t|}| d}t	d|}| j
}|D ]0}tj|s|tjtjfkrqtj||}q|r|d7 }|S )	zTranslate a /-separated PATH to the local filename syntax.

        Components that mean special things to the local file system
        (e.g. drive or directory names) are ignored.  (XXX They should
        probably be diagnosed.)

        ?r	   r   #r   r   r   N)r*   r(   r   r   r   r   r   	posixpathnormpathfilterr   r   r2   dirnamecurdirpardirrm   )r   r2   Ztrailing_slashr<   Zwordr   r   r   r   )  s$    	


z'SimpleHTTPRequestHandler.translate_pathc                 C   s   t || dS )a  Copy all data between two file objects.

        The SOURCE argument is a file object open for reading
        (or anything with a read() method) and the DESTINATION
        argument is a file object open for writing (or
        anything with a write() method).

        The only reason for overriding this would be to change
        the block size or perhaps to replace newlines by CRLF
        -- note however that this the default server uses this
        to copy binary data as well.

        N)shutilZcopyfileobj)r   sourceZ
outputfiler   r   r   r   G  s    z!SimpleHTTPRequestHandler.copyfilec                 C   sL   t |\}}|| jkr"| j| S | }|| jkr>| j| S | jd S dS )a  Guess the type of a file.

        Argument is a PATH (a filename).

        Return value is a string of the form type/subtype,
        usable for a MIME Content-type header.

        The default implementation looks the file's extension
        up in the table self.extensions_map, using application/octet-stream
        as a default; however it would be permissible (if
        slow) to look inside the data to make a better guess.

        r   N)r   splitextextensions_mapr9   )r   r2   baseZextr   r   r   r   W  s    



z#SimpleHTTPRequestHandler.guess_typezapplication/octet-streamz
text/plain)r   .pyz.cz.h)r   r   r   r   r   rz   r   r   r   r   r   r   r   r   	mimetypesZinitedZinitZ	types_mapcopyr   update__classcell__r   r   r   r   r   t  s&   	W:
c           	      C   s   |  d\} }}tj| } | d}g }|dd D ],}|dkrL|  q6|r6|dkr6|| q6|r| }|r|dkr|  d}q|dkrd}nd}|rd||f}dd| |f}d|}|S )a  
    Given a URL path, remove extra '/'s and '.' path elements and collapse
    any '..' references and returns a collapsed path.

    Implements something akin to RFC-2396 5.2 step 6 to parse relative paths.
    The utility of this function is limited to is_cgi method and helps
    preventing some security attacks.

    Returns: The reconstituted URL, which will always start with a '/'.

    Raises: IndexError if too many '..' occur within the path.

    r   r   Nr   z..r   r   )	partitionr   r   r   r*   poprh   rm   )	r2   _query
path_partsZ
head_partspartZ	tail_partZ	splitpathcollapsed_pathr   r   r   _url_collapse_path|  s.    


r   c                  C   sr   t rt S zddl} W n tk
r*   Y dS X z| dd a W n. tk
rl   dtdd |  D  a Y nX t S )	z$Internal routine to get nobody's uidr   Nr   nobodyr
   r	   c                 s   s   | ]}|d  V  qdS )r
   Nr   )r   r   r   r   r   	<genexpr>  s     znobody_uid.<locals>.<genexpr>)r   pwdImportErrorgetpwnamrW   maxZgetpwall)r   r   r   r   
nobody_uid  s     r   c                 C   s   t | t jS )zTest for executable file.)r   accessX_OK)r2   r   r   r   
executable  s    r   c                   @   sV   e Zd ZdZeedZdZdd Zdd Z	dd	 Z
d
dgZdd Zdd Zdd ZdS )r   zComplete HTTP server with GET, HEAD and POST commands.

    GET and HEAD also support running CGI scripts.

    The POST command is *only* implemented for CGI scripts.

    forkr   c                 C   s$   |   r|   n| tjd dS )zRServe a POST request.

        This is only implemented for CGI scripts.

        zCan only POST to CGI scriptsN)is_cgirun_cgir0   r   rD   rA   r   r   r   do_POST  s    
zCGIHTTPRequestHandler.do_POSTc                 C   s   |   r|  S t| S dS )z-Version of send_head that support CGI scriptsN)r   r   r   r   rA   r   r   r   r     s    zCGIHTTPRequestHandler.send_headc                 C   sP   t | j}|dd}|d| ||d d  }}|| jkrL||f| _dS dS )a3  Test whether self.path corresponds to a CGI script.

        Returns True and updates the cgi_info attribute to the tuple
        (dir, rest) if self.path requires running a CGI script.
        Returns False otherwise.

        If any exception is raised, the caller should assume that
        self.path was rejected as invalid and act accordingly.

        The default implementation tests whether the normalized url
        path begins with one of the strings in self.cgi_directories
        (and the next character is a '/' or the end of the string).

        r   r	   NTF)r   r2   findcgi_directoriescgi_info)r   r   Zdir_sepheadtailr   r   r   r     s    


zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbinc                 C   s   t |S )z1Test whether argument path is an executable file.)r   )r   r2   r   r   r   is_executable  s    z#CGIHTTPRequestHandler.is_executablec                 C   s   t j|\}}| dkS )z.Test whether argument path is a Python script.)r   z.pyw)r   r2   r   r9   )r   r2   r   r   r   r   r   	is_python  s    zCGIHTTPRequestHandler.is_pythonc           )   	   C   s  | j \}}|d | }|dt|d }|dkr|d| }||d d }| |}tj|r|| }}|dt|d }q*qq*|d\}}}	|d}|dkr|d| ||d  }
}n
|d }
}|d |
 }| |}tj|s
| 	t
jd|  dS tj|s.| 	t
jd|  dS | |}| jsF|sh| |sh| 	t
jd	|  dS ttj}|  |d
< | jj|d< d|d< | j|d< t| jj|d< | j|d< tj|}||d< | ||d< ||d< |	r|	|d< | jd |d< | j d}|r|! }t|dkrddl"}ddl#}|d |d< |d $ dkrz"|d %d}|&|'d}W n |j(t)fk
r   Y n&X |!d}t|dkr|d |d< | j ddkr| j* |d< n| jd |d< | j d}|r||d < | j d!}|r||d"< g }| j+d#D ]>}|dd d$krR|,|-  n||d%d !d& }q,d&.||d'< | j d(}|r||d)< t/d| j0d*g }d+.|}|r||d,< d-D ]}|1|d q| 2t
j3d. | 4  |	5d/d0}| jr|
g}d1|kr|,| t6 }| j78  t9 }|dkrt:|d\}}t;;| j<gg g dd r~| j<=dsNq~qN|r| >d2| dS z\zt?| W n t@k
r   Y nX tA| j<B d tA| j7B d tC||| W n(   | jD| jE| j tFd3 Y nX nddlG} |g}!| |rrtHjI}"|"$ Jd4rf|"dd5 |"d6d  }"|"d7g|! }!d1|	kr|!,|	 | Kd8| L|! ztM|}#W n tNtOfk
r   d}#Y nX | jP|!| jQ| jQ| jQ|d9}$| j$ d:kr|#dkr| j<=|#}%nd}%t;;| j<jRgg g dd r>| j<jRSds
q>q
|$T|%\}&}'| j7U|& |'rj| >d;|' |$jVW  |$jXW  |$jY}(|(r| >d2|( n
| Kd< dS )=zExecute a CGI script.r   r	   r   Nr   r   zNo such CGI script (%r)z#CGI script is not a plain file (%r)z!CGI script is not executable (%r)ZSERVER_SOFTWAREZSERVER_NAMEzCGI/1.1ZGATEWAY_INTERFACEZSERVER_PROTOCOLZSERVER_PORTZREQUEST_METHODZ	PATH_INFOZPATH_TRANSLATEDZSCRIPT_NAMEQUERY_STRINGZREMOTE_ADDRauthorizationr
   Z	AUTH_TYPEZbasicascii:ZREMOTE_USERzcontent-typeZCONTENT_TYPEzcontent-lengthCONTENT_LENGTHrefererHTTP_REFERERacceptz	
    ,ZHTTP_ACCEPTz
user-agentHTTP_USER_AGENTZcookiez, HTTP_COOKIE)r  ZREMOTE_HOSTr  r  r  r  zScript output follows+ry   =zCGI script exit status %#x   zw.exez-uzcommand: %s)stdinstdoutrv   envZpostz%szCGI script exited OK)Zr   r   r+   r   r   r2   r   r   r   r0   r   r   isfileZ	FORBIDDENr  	have_forkr   r   Zdeepcopyenvironrb   Zserverr   r1   r&   r   r"   r   r   r   r   r7   r8   r*   base64binasciir9   r^   ZdecodebytesdecodeErrorUnicodeErrorZget_content_typeZgetallmatchingheadersrh   striprm   r   Zget_all
setdefaultrX   r   rk   rT   r   rF   rG   r   waitpidselectr5   readrH   setuidr   dup2r   execveZhandle_errorZrequest_exit
subprocessru   r   r   rp   Zlist2cmdliner.   r   r-   PopenPIPEZ_sockZrecvZcommunicater`   rv   r    r  
returncode))r   dirrestr2   iZnextdirZnextrestZ	scriptdirr   r   ZscriptZ
scriptnameZ
scriptfileZispyr  Zuqrestr  r  r  Zlengthr  r	  lineZuacoZ
cookie_strkZdecoded_queryrt   r   pidstsr'  ZcmdlineZinterpnbytespdatar  rv   Zstatusr   r   r   r     s<   




















zCGIHTTPRequestHandler.run_cgiN)r   r   r   r   rC   r   r  Zrbufsizer   r   r   r   r   r  r   r   r   r   r   r     s   	
c                  G   s4   t j| t jt jd}tt|\}}}}}||fS )N)typeflags)r   ZgetaddrinfoZSOCK_STREAMZ
AI_PASSIVEnextiter)ZaddressZinfosZfamilyr6  protoZ	canonnameZsockaddrr   r   r   _get_best_family  s    r;  r   i@  c           	      C   s   t ||\|_}|| _||| }|j dd \}}d|krLd| dn|}td| d| d| d| d		 z|  W n& tk
r   td
 t	d Y nX W 5 Q R X dS )zmTest the HTTP request handler class.

    This runs an HTTP server on port 8000 (or the port argument).

    Nr
   r  []zServing HTTP on z port z	 (http://z/) ...z&
Keyboard interrupt received, exiting.r   )
r;  Zaddress_familyr1   r   ZgetsocknameprintZserve_foreverKeyboardInterruptru   exit)	HandlerClassServerClassZprotocolr   bindZaddrZhttpdr   Zurl_hostr   r   r   test  s    rD  __main__z--cgi
store_truezRun as CGI Server)actionhelpz--bindz-bZADDRESSz8Specify alternate bind address [default: all interfaces])metavarrH  z--directoryz-dz9Specify alternative directory [default:current directory])defaultrH  r   Zstorer   z&Specify alternate port [default: 8000])rG  rJ  r6  nargsrH  r   c                       s   e Zd Z fddZ  ZS )DualStackServerc              	      s4   t t | jtjtjd W 5 Q R X t  S )Nr   )	
contextlibsuppress	Exceptionr   Z
setsockoptZIPPROTO_IPV6ZIPV6_V6ONLYr   r   rA   r   r   r   r     s      zDualStackServer.server_bind)r   r   r   r   r   r   r   r   r   rL    s   rL  )rA  rB  r   rC  )9r   r   __all__r   r   Zemail.utilsr}   r\   Zhttp.clientr3   r   r   r   r   r!  r   r   r   ru   r|   Zurllib.parser   rM  	functoolsr   r   r   r   r   r   ZThreadingMixInr   ZStreamRequestHandlerr   r   r   r   r   r   r   r;  rD  r   argparseArgumentParserparseradd_argumentr   r.   
parse_argsrt   ZcgiZhandler_classr   rL  r   rC  r   r   r   r   <module>   s   R      c  
0  
  


 