AlkantarClanX12

Your IP : 3.142.210.173


Current Path : /opt/alt/python38/lib64/python3.8/http/__pycache__/
Upload File :
Current File : //opt/alt/python38/lib64/python3.8/http/__pycache__/server.cpython-38.opt-1.pyc

U

i�f��@s
dZdZdddddgZddlZddlZddlZddlZddlZ	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZdd	lmZdd
l	mZdZdZGd
d�dej�ZGdd�deje�Z Gdd�dej!�Z"Gdd�de"�Z#dd�Z$da%dd�Z&dd�Z'Gdd�de#�Z(dd�Z)e"e dddfdd�Z*e+dk�rddl,Z,e,�-�Z.e.j/dd d!d"�e.j/d#d$d%d&d'�e.j/d(d)e
�0�d*d+�e.j/d,d-de1d.d/d0�e.�2�Z3e3j4�r�e(Z5nee#e3j6d1�Z5Gd2d3�d3e �Z7e*e5e7e3j8e3j9d4�dS)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
z0.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>
ztext/html;charset=utf-8c@seZdZdZdd�ZdS)r�cCs4tj�|�|jdd�\}}t�|�|_||_dS)z.Override server_bind to store the server name.N�)�socketserver�	TCPServer�server_bindZserver_address�socketZgetfqdn�server_name�server_port)�self�host�port�r�0/opt/alt/python38/lib64/python3.8/http/server.pyr
�szHTTPServer.server_bindN)�__name__�
__module__�__qualname__Zallow_reuse_addressr
rrrrr�sc@seZdZdZdS)rTN)rrrZdaemon_threadsrrrrr�sc
@sJeZdZdZdej��dZdeZ	e
ZeZ
dZdd�Zdd	�Zd
d�Zdd
�ZdFdd�ZdGdd�ZdHdd�Zdd�Zdd�Zdd�ZdIdd�Zdd�Ze�d d!�e�ed"�ed#d$��D��Z d%e e!d&�<d'd(�Z"d)d*�Z#dJd+d,�Z$d-d.�Z%d/d0d1d2d3d4d5gZ&dd6d7d8d9d:d;d<d=d>d?d@dAg
Z'dBdC�Z(dDZ)e*j+j,Z-dEd!�e.j/�0�D�Z1dS)Kra�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".

    zPython/rz	BaseHTTP/�HTTP/0.9c
Cs�d|_|j|_}d|_t|jd�}|�d�}||_|��}t	|�dkrLdSt	|�dk�r&|d}zT|�
d	�srt�|�d
d�d}|�d�}t	|�d
kr�t�t|d�t|d�f}Wn,tt
fk
r�|�tjd|�YdSX|dk�r|jdk�rd|_|dk�r |�tjd|�dS||_d
t	|�k�rBdk�sZn|�tjd|�dS|dd
�\}}t	|�d
k�r�d|_|dk�r�|�tjd|�dS|||_|_|j�
d��r�d
|j�d
�|_ztjj|j|jd�|_Wn�tjjk
�r(}z|�tjdt|��WY�dSd}~XYnBtjjk
�rh}z|�tjdt|��WY�dSd}~XYnX|j�dd�}	|	��dk�r�d|_n |	��dk�r�|jdk�r�d|_|j�dd�}
|
��dk�r�|jdk�r�|jdk�r�|� ��s�dSdS) aHParse 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
rF����zHTTP/�/r	�.r
zBad request version (%r))r	r	zHTTP/1.1)r
rzInvalid HTTP version (%s)zBad request syntax (%r)ZGETzBad HTTP/0.9 request type (%r)z//)Z_classz
Line too longzToo many headers�
Connection��close�
keep-aliveZExpectz100-continue)!�command�default_request_version�request_version�close_connection�str�raw_requestline�rstrip�requestline�split�len�
startswith�
ValueError�int�
IndexError�
send_errorrZBAD_REQUEST�protocol_versionZHTTP_VERSION_NOT_SUPPORTED�path�lstrip�http�clientZ
parse_headers�rfile�MessageClass�headersZLineTooLongZREQUEST_HEADER_FIELDS_TOO_LARGEZ
HTTPException�get�lower�handle_expect_100)r�versionr)�wordsZbase_version_numberZversion_numberr"r2�errZconntypeZexpectrrr�
parse_requests�


�
��
�
������
z$BaseHTTPRequestHandler.parse_requestcCs|�tj�|��dS)a7Decide 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_onlyrZCONTINUE�end_headers�rrrrr;xsz(BaseHTTPRequestHandler.handle_expect_100c
Cs�z�|j�d�|_t|j�dkrBd|_d|_d|_|�tj	�WdS|jsTd|_
WdS|��sbWdSd|j}t||�s�|�tj
d|j�WdSt||�}|�|j��Wn<tjk
r�}z|�d|�d|_
WY�dSd}~XYnXdS)	z�Handle 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.

        iirNTZdo_zUnsupported method (%r)zRequest timed out: %r)r6�readliner'r+r)r$r"r0rZREQUEST_URI_TOO_LONGr%r?�hasattr�NOT_IMPLEMENTED�getattr�wfile�flushrZtimeout�	log_error)rZmname�method�errr�handle_one_request�s6

�
z)BaseHTTPRequestHandler.handle_one_requestcCs"d|_|��|js|��qdS)z&Handle multiple requests if necessary.TN)r%rLrBrrr�handle�szBaseHTTPRequestHandler.handleNcCsz|j|\}}Wntk
r.d\}}YnX|dkr<|}|dkrH|}|�d||�|�||�|�dd�d}|dkr�|tjtjtjfkr�|j	|t
j|dd�t
j|dd�d	�}|�d
d�}|�d|j
�|�d
tt|���|��|jdk�r|�r|j�|�dS)akSend 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.

        )�???rNNzcode %d, message %srr ��F��quote)�code�message�explainzUTF-8�replacezContent-Type�Content-LengthZHEAD)�	responses�KeyErrorrI�
send_response�send_headerrZ
NO_CONTENTZ
RESET_CONTENT�NOT_MODIFIED�error_message_format�html�escape�encode�error_content_typer&r+rAr"rG�write)rrRrSrTZshortmsgZlongmsgZbodyZcontentrrrr0�s:���z!BaseHTTPRequestHandler.send_errorcCs:|�|�|�||�|�d|���|�d|���dS)z�Add 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.

        ZServerZDateN)�log_requestr@rZ�version_string�date_time_string�rrRrSrrrrY�s
z$BaseHTTPRequestHandler.send_responsecCsd|jdkr`|dkr0||jkr,|j|d}nd}t|d�s@g|_|j�d|j||f�dd��dS)	zSend the response header only.rNrr�_headers_bufferz
%s %d %s
�latin-1�strict)r$rWrDrf�appendr1r_rerrrr@�s



��z)BaseHTTPRequestHandler.send_response_onlycCsl|jdkr6t|d�sg|_|j�d||f�dd��|��dkrh|��dkrVd|_n|��d	krhd
|_dS)z)Send a MIME header to the headers buffer.rrfz%s: %s
rgrhZ
connectionr Tr!FN)r$rDrfrir_r:r%)r�keyword�valuerrrrZs

�z"BaseHTTPRequestHandler.send_headercCs"|jdkr|j�d�|��dS)z,Send the blank line ending the MIME headers.rs
N)r$rfri�
flush_headersrBrrrrAs
z"BaseHTTPRequestHandler.end_headerscCs(t|d�r$|j�d�|j��g|_dS)Nrf�)rDrGra�joinrfrBrrrrls
z$BaseHTTPRequestHandler.flush_headers�-cCs.t|t�r|j}|�d|jt|�t|��dS)zNLog an accepted request.

        This is called by send_response().

        z
"%s" %s %sN)�
isinstancerrk�log_messager)r&)rrR�sizerrrrb s
�z"BaseHTTPRequestHandler.log_requestcGs|j|f|��dS)z�Log 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)rq)r�format�argsrrrrI+sz BaseHTTPRequestHandler.log_errorcCsi|]}|d|d���qS)z\xZ02xr)�.0�crrr�
<dictcomp>;sz!BaseHTTPRequestHandler.<dictcomp>� ��z\\�\cGs2||}tj�d|��|��|�|j�f�dS)aZLog 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.

        Unicode control characters are replaced with escaped hex
        before writing the output to stderr.

        z%s - - [%s] %s
N)�sys�stderrra�address_string�log_date_time_string�	translate�_control_char_table)rrsrtrSrrrrq>s
��z"BaseHTTPRequestHandler.log_messagecCs|jd|jS)z*Return the server software version string.� )�server_version�sys_versionrBrrrrcXsz%BaseHTTPRequestHandler.version_stringcCs |dkrt��}tjj|dd�S)z@Return the current date and time formatted for a message header.NT)Zusegmt)�time�email�utilsZ
formatdate)rZ	timestamprrrrd\sz'BaseHTTPRequestHandler.date_time_stringc	CsBt��}t�|�\	}}}}}}}}	}
d||j|||||f}|S)z.Return the current time formatted for logging.z%02d/%3s/%04d %02d:%02d:%02d)r��	localtime�	monthname)rZnowZyearZmonthZdayZhhZmmZss�x�y�z�srrrrbs�z+BaseHTTPRequestHandler.log_date_time_stringZMonZTueZWedZThuZFriZSatZSunZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDeccCs
|jdS)zReturn the client address.r)�client_addressrBrrrr~psz%BaseHTTPRequestHandler.address_string�HTTP/1.0cCsi|]}||j|jf�qSr)�phraseZdescription)ru�vrrrrws�)NN)N)N)roro)N)2rrr�__doc__r|r<r*r��__version__r��DEFAULT_ERROR_MESSAGEr\�DEFAULT_ERROR_CONTENT_TYPEr`r#r?r;rLrMr0rYr@rZrArlrbrIr&�	maketrans�	itertools�chain�ranger��ordrqrcrdrZweekdaynamer�r~r1r4r5ZHTTPMessager7r�__members__�valuesrWrrrrr�s^gj%
5


�
�	�cs�eZdZdZdeZdd��fdd�
Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
ejsle��ej��Ze�ddddd���ZS)raWSimple 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.

    zSimpleHTTP/N��	directorycs(|dkrt��}||_t�j||�dS�N)�os�getcwdr��super�__init__)rr�rt�kwargs��	__class__rrr��sz!SimpleHTTPRequestHandler.__init__cCs.|��}|r*z|�||j�W5|��XdS)zServe a GET request.N)�	send_headr �copyfilerG�r�frrr�do_GET�s
zSimpleHTTPRequestHandler.do_GETcCs|��}|r|��dS)zServe a HEAD request.N)r�r r�rrr�do_HEAD�sz SimpleHTTPRequestHandler.do_HEADcCs^|�|j�}d}tj�|�r�tj�|j�}|j�d�s�|�t	j
�|d|d|dd|d|df}tj�|�}|�d|�|�
�dSd	D]&}tj�||�}tj�|�r�|}q�q�|�|�S|�|�}|�d�r�|�t	jd
�dSzt|d�}Wn&tk
�r|�t	jd
�YdSX�z"t�|���}d|jk�r�d
|jk�r�ztj�|jd�}	Wnttttfk
�r|YnzX|	j dk�r�|	j!t"j#j$d�}	|	j t"j#j$k�r�t"j"�%|j&t"j#j$�}
|
j!dd�}
|
|	k�r�|�t	j'�|�
�|�(�WdS|�t	j)�|�d|�|�dt*|d��|�d|�+|j&��|�
�|WS|�(��YnXdS)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.

        Nrrr	r
r�ZLocation)z
index.htmlz	index.htmzFile not found�rbzIf-Modified-Sincez
If-None-Match)�tzinfo)Zmicrosecond�Content-typerV�z
Last-Modified),�translate_pathr2r��isdir�urllib�parseZurlsplit�endswithrYrZMOVED_PERMANENTLYZ
urlunsplitrZrArn�exists�list_directory�
guess_typer0�	NOT_FOUND�open�OSError�fstat�filenor8r�r�Zparsedate_to_datetime�	TypeErrorr/�
OverflowErrorr-r�rU�datetime�timezoneZutcZ
fromtimestamp�st_mtimer[r �OKr&rd)rr2r��partsZ	new_partsZnew_url�indexZctypeZfsZimsZ
last_modifrrrr��s��


���

�z"SimpleHTTPRequestHandler.send_headc
	Cs�zt�|�}Wn$tk
r2|�tjd�YdSX|jdd�d�g}ztjj	|j
dd�}Wn"tk
r�tj�	|j
�}YnXtj
|dd	�}t��}d
|}|�d�|�d�|�d
|�|�d|�|�d|�|�d�|D]v}tj
�||�}|}	}
tj
�|��r$|d}	|d}
tj
�|��r:|d}	|�dtjj|
dd�tj
|	dd	�f�q�|�d�d�|��|d�}t��}|�|�|�d�|�tj�|�dd|�|�dtt|���|��|S)z�Helper 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().

        zNo permission to list directoryNcSs|��Sr�)r:)�arrr�<lambda>rmz9SimpleHTTPRequestHandler.list_directory.<locals>.<lambda>)�key�
surrogatepass��errorsFrPzDirectory 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>
�
�surrogateescaperr�ztext/html; charset=%srV) r��listdirr�r0rr��sortr�r��unquoter2�UnicodeDecodeErrorr]r^r|�getfilesystemencodingrirnr��islinkrQr_�io�BytesIOra�seekrYr�rZr&r+rA)
rr2�list�rZdisplaypath�enc�title�name�fullnameZdisplaynameZlinknameZencodedr�rrrr�sh�
�


�
���


z'SimpleHTTPRequestHandler.list_directorycCs�|�dd�d}|�dd�d}|���d�}ztjj|dd�}Wn tk
rbtj�|�}YnXt�|�}|�d�}t	d|�}|j
}|D]0}tj�
|�s�|tjtjfkr�q�tj�||�}q�|r�|d7}|S)	z�Translate 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�#rr�r�N)r*r(r�r�r�r�r��	posixpath�normpath�filterr�r�r2�dirname�curdir�pardirrn)rr2Ztrailing_slashr=Zwordrrrr�:s$	


z'SimpleHTTPRequestHandler.translate_pathcCst�||�dS)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)�shutilZcopyfileobj)r�sourceZ
outputfilerrrr�Xsz!SimpleHTTPRequestHandler.copyfilecCsLt�|�\}}||jkr"|j|S|��}||jkr>|j|S|jdSdS)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.

        rN)r��splitext�extensions_mapr:)rr2�baseZextrrrr�hs



z#SimpleHTTPRequestHandler.guess_typezapplication/octet-streamz
text/plain)r�.pyz.cz.h)rrrr�r�r�r�r�r�r�r�r�r�r��	mimetypesZinitedZinitZ	types_map�copyr��update�
__classcell__rrr�rr�s&	W:
�c	Cs�|�d�\}}}tj�|�}|�d�}g}|dd�D],}|dkrL|��q6|r6|dkr6|�|�q6|r�|��}|r�|dkr�|��d}q�|dkr�d}nd}|r�d�||f�}dd�|�|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�rNrz..rr)�	partitionr�r�r�r*�poprirn)	r2�_�query�
path_partsZ
head_parts�partZ	tail_partZ	splitpath�collapsed_pathrrr�_url_collapse_path�s.


r�cCsrtrtSzddl}Wntk
r*YdSXz|�d�daWn.tk
rldtdd�|��D��aYnXtS)	z$Internal routine to get nobody's uidrNr�nobodyr
r	css|]}|dVqdS)r
Nr)rur�rrr�	<genexpr>�sznobody_uid.<locals>.<genexpr>)r��pwd�ImportError�getpwnamrX�maxZgetpwall)r�rrr�
nobody_uid�s r�cCst�|tj�S)zTest for executable file.)r��access�X_OK)r2rrr�
executable�src@sVeZdZdZeed�ZdZdd�Zdd�Z	dd	�Z
d
dgZdd
�Zdd�Z
dd�ZdS)rz�Complete 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.

    �forkrcCs$|��r|��n|�tjd�dS)zRServe a POST request.

        This is only implemented for CGI scripts.

        zCan only POST to CGI scriptsN)�is_cgi�run_cgir0rrErBrrr�do_POST�s
�zCGIHTTPRequestHandler.do_POSTcCs|��r|��St�|�SdS)z-Version of send_head that support CGI scriptsN)rrrr�rBrrrr��szCGIHTTPRequestHandler.send_headcCsPt|j�}|�dd�}|d|�||dd�}}||jkrL||f|_dSdS)a3Test 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).

        rr	NTF)r�r2�find�cgi_directories�cgi_info)rr�Zdir_sep�head�tailrrrr�s


zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbincCst|�S)z1Test whether argument path is an executable file.)r)rr2rrr�
is_executablesz#CGIHTTPRequestHandler.is_executablecCstj�|�\}}|��dkS)z.Test whether argument path is a Python script.)r�z.pyw)r�r2r�r:)rr2r
rrrr�	is_pythonszCGIHTTPRequestHandler.is_pythonc)	Cs�|j\}}|d|}|�dt|�d�}|dkr�|d|�}||dd�}|�|�}tj�|�r�||}}|�dt|�d�}q*q�q*|�d�\}}}	|�d�}|dkr�|d|�||d�}
}n
|d}
}|d|
}|�|�}tj�|��s
|�	t
jd|�dStj�|��s.|�	t
j
d|�dS|�|�}
|j�sF|
�sh|�|��sh|�	t
j
d	|�dSt�tj�}|��|d
<|jj|d<d|d
<|j|d<t|jj�|d<|j|d<tj�|�}||d<|�|�|d<||d<|	�r�|	|d<|jd|d<|j� d�}|�r�|�!�}t|�dk�r�ddl"}ddl#}|d|d<|d�$�dk�r�z"|d�%d�}|�&|��'d�}Wn|j(t)fk
�r�Yn&X|�!d�}t|�dk�r�|d|d<|j� d�dk�r�|j�*�|d<n|jd|d<|j� d�}|�r||d <|j� d!�}|�r||d"<g}|j�+d#�D]>}|dd�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�}|j7�8�t�9�}|dk�r�t�:|d�\}}t;�;|j<gggd�d�r~|j<�=d��sN�q~�qN|�r�|�>d2|�dSz\zt�?|�Wnt@k
�r�YnXt�A|j<�B�d�t�A|j7�B�d�t�C|||�Wn(|j�D|jE|j�t�Fd3�YnX�n�ddlG} |g}!|�|��rrtHjI}"|"�$��Jd4��rf|"dd5�|"d6d�}"|"d7g|!}!d1|	k�r�|!�,|	�|�Kd8| �L|!��ztM|�}#WntNtOfk
�r�d}#YnX| jP|!| jQ| jQ| jQ|d9�}$|j�$�d:k�r|#dk�r|j<�=|#�}%nd}%t;�;|j<jRgggd�d�r>|j<jR�Sd��s
�q>�q
|$�T|%�\}&}'|j7�U|&�|'�rj|�>d;|'�|$jV�W�|$jX�W�|$jY}(|(�r�|�>d2|(�n
|�Kd<�dS)=zExecute a CGI script.rr	rNr�rzNo such CGI script (%r)z#CGI script is not a plain file (%r)z!CGI script is not executable (%r)ZSERVER_SOFTWAREZSERVER_NAMEzCGI/1.1ZGATEWAY_INTERFACEZSERVER_PROTOCOLZSERVER_PORTZREQUEST_METHODZ	PATH_INFOZPATH_TRANSLATEDZSCRIPT_NAME�QUERY_STRINGZREMOTE_ADDR�
authorizationr
Z	AUTH_TYPEZbasic�ascii�:ZREMOTE_USERzcontent-typeZCONTENT_TYPEzcontent-length�CONTENT_LENGTH�referer�HTTP_REFERER�acceptz	

 ��,ZHTTP_ACCEPTz
user-agent�HTTP_USER_AGENTZcookiez, �HTTP_COOKIE)rZREMOTE_HOSTrrrrzScript output follows�+r��=zCGI script exit status %#xryzw.exe������z-uzcommand: %s)�stdin�stdoutr}�envZpostz%szCGI script exited OK)Zr	rr+r�r�r2r�r�r�r0rr��isfileZ	FORBIDDENr
�	have_forkrr�Zdeepcopy�environrcZserverrr1r&rr"r�r�r�r�r8r9r*�base64�binasciir:r_Zdecodebytes�decode�Error�UnicodeErrorZget_content_typeZgetallmatchingheadersri�striprnr�Zget_all�
setdefaultrYr�rlrUr�rGrHr�waitpid�selectr6�readrI�setuidr��dup2r��execveZhandle_errorZrequest�_exit�
subprocessr|rr�rqZlist2cmdliner.r�r-�Popen�PIPEZ_sockZrecvZcommunicaterar}r r�
returncode))r�dir�restr2�iZnextdirZnextrestZ	scriptdirr�r�ZscriptZ
scriptnameZ
scriptfileZispyr Zuqrestrr$r%Zlengthrr�lineZua�coZ
cookie_str�kZ
decoded_queryrtr��pid�stsr2ZcmdlineZinterp�nbytes�p�datarr}Zstatusrrrrs<





��
�


�








�

zCGIHTTPRequestHandler.run_cgiN)rrrr�rDr�r"Zrbufsizerr�rrrr
rrrrrr�s	
cGs4tj|tjtjd��}tt|��\}}}}}||fS)N)�type�flags)rZgetaddrinfoZSOCK_STREAMZ
AI_PASSIVE�next�iter)ZaddressZinfosZfamilyrA�protoZ	canonnameZsockaddrrrr�_get_best_family�s�rFr�i@c	Cs�t||�\|_}||_|||���}|j��dd�\}}d|krLd|�d�n|}td|�d|�d|�d|�d	�	�z|��Wn&tk
r�td
�t�	d�YnXW5QRXdS)zmTest the HTTP request handler class.

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

    Nr
r�[�]zServing HTTP on z port z	 (http://z/) ...z&
Keyboard interrupt received, exiting.r)
rFZaddress_familyr1rZgetsockname�printZ
serve_forever�KeyboardInterruptr|�exit)	�HandlerClass�ServerClassZprotocolr�bindZaddrZhttpdrZurl_hostrrr�test�s�rO�__main__z--cgi�
store_truezRun as CGI Server)�action�helpz--bindz-bZADDRESSz8Specify alternate bind address [default: all interfaces])�metavarrSz--directoryz-dz9Specify alternative directory [default:current directory])�defaultrSrZstorer�z&Specify alternate port [default: 8000])rRrUrA�nargsrSr�cseZdZ�fdd�Z�ZS)�DualStackServerc	s4t�t��|j�tjtjd�W5QRXt���S)Nr)	�
contextlib�suppress�	ExceptionrZ
setsockoptZIPPROTO_IPV6ZIPV6_V6ONLYr�r
rBr�rrr
s�zDualStackServer.server_bind)rrrr
r�rrr�rrWsrW)rLrMrrN):r�r��__all__r�r�Zemail.utilsr�r]Zhttp.clientr4r�r�r�r�r�r,r�rrr|r�Zurllib.parser�rX�	functoolsrrr�r�rrZThreadingMixInrZStreamRequestHandlerrrr�r�r�rrrFrOr�argparse�ArgumentParser�parser�add_argumentr�r.�
parse_argsrtZcgiZ
handler_classr�rWrrNrrrr�<module>s�R�s
0
�

�
�����