AlkantarClanX12

Your IP : 3.16.82.182


Current Path : /opt/alt/python34/lib64/python3.4/http/__pycache__/
Upload File :
Current File : //opt/alt/python34/lib64/python3.4/http/__pycache__/server.cpython-34.pyc

�
e fA��@sUdZdZddddgZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZdZd	Zd
d�ZGdd�de
j�ZGd
d�de
j�ZGdd�de�Zdd�Zdadd�Zdd�ZGdd�de�Z eeddddd�Z!e"dkrQej#�Z$e$j%ddddd �e$j%d!d"d#dd$d%dd&�e$j%d'dd(d#dd)e&d*d+dd,�e$j'�Z(e(j)r)e Z*neZ*e!d-e*d'e(j+d.e(j,�ndS)/a@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�BaseHTTPRequestHandler�SimpleHTTPRequestHandler�CGIHTTPRequestHandler�Na�<!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-8cCs(|jdd�jdd�jdd�S)N�&z&amp;�<z&lt;�>z&gt;)�replace)�html�r�0/opt/alt/python34/lib64/python3.4/http/server.py�_quote_htmlsr
c@s"eZdZdZdd�ZdS)r�cCsNtjj|�|jj�dd�\}}tj|�|_||_dS)z.Override server_bind to store the server name.N�)�socketserver�	TCPServer�server_bind�socket�getsocknameZgetfqdn�server_name�server_port)�self�host�portrrrr�szHTTPServer.server_bindN)�__name__�
__module__�__qualname__Zallow_reuse_addressrrrrrr�sc
@s�eZdZdZdejj�dZdeZ	e
ZeZ
dZdd�Zdd	�Zd
d�Zdd
�Zdddd�Zddd�Zddd�Zdd�Zdd�Zdd�Zdddd�Zdd�Zd d!�Zd"d#�Zdd$d%�Zd&d'�Zd(d)d*d+d,d-d.gZdd/d0d1d2d3d4d5d6d7d8d9d:g
Z d;d<�Z!d=Z"e#j$j%Z&i,d�d@6d�dC6d�dF6d�dI6d�dL6d�dO6d�dR6d�dU6d�dX6d�d[6d�d^6d�da6d�dd6d�dg6d�dj6d�dl6d�do6d�dr6d�du6d�dx6d�d{6d�d~6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6d�d�6Z'dS)�ra�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/zHTTP/0.9c
Cs)d|_|j|_}d|_t|jd�}|jd�}||_|j�}t	|�dkr�|\}}}|dd�dkr�|j
dd	|�d
Syd|jdd�d}|jd
�}t	|�dkr�t�nt|d�t|d�f}Wn0tt
fk
r=|j
dd	|�d
SYnX|dkre|jdkred
|_n|dkr�|j
dd|�d
Snpt	|�dkr�|\}}d|_|dkr�|j
dd|�d
Sn"|s�d
S|j
dd|�d
S||||_|_|_y%tjj|jd|j�|_Wn,tjjk
rl|j
dd�d
SYnX|jjdd�}|j�dkr�d|_n-|j�dkr�|jdkr�d
|_n|jjdd�}	|	j�dkr%|jdkr%|jdkr%|j�s%d
SndS) a'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, an
        error is sent back.

        NTz
iso-8859-1z
��zHTTP/i�zBad request version (%r)F�/r�.rrzHTTP/1.1i�zInvalid HTTP Version (%s)ZGETzBad HTTP/0.9 request type (%r)zBad request syntax (%r)Z_classz
Line too long�
Connection��closez
keep-aliveZExpectz100-continue)rr)rr)�command�default_request_version�request_version�close_connection�str�raw_requestline�rstrip�requestline�split�len�
send_error�
ValueError�int�
IndexError�protocol_version�path�http�clientZ
parse_headers�rfile�MessageClass�headersZLineTooLong�get�lower�handle_expect_100)
r�versionr+�wordsr$r3Zbase_version_numberZversion_numberZconntypeZexpectrrr�
parse_requestst				$					z$BaseHTTPRequestHandler.parse_requestcCs|jd�|j�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.

        �dT)�send_response_only�end_headers)rrrrr;Xs

z(BaseHTTPRequestHandler.handle_expect_100cCs&y�|jjd�|_t|j�dkrYd|_d|_d|_|jd�dS|jsod|_dS|j	�sdSd|j}t
||�s�|jdd	|j�dSt||�}|�|jj
�WnEtjk
r!}z"|jd
|�d|_dSWYdd}~XnXdS)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.

        iir"i�NTZdo_i�zUnsupported method (%r)zRequest timed out: %r)r6�readliner)r-r+r&r$r.r'r>�hasattr�getattr�wfile�flushrZtimeout�	log_error)rZmname�method�errr�handle_one_requestjs0			
		
	z)BaseHTTPRequestHandler.handle_one_requestcCs1d|_|j�x|js,|j�qWdS)z&Handle multiple requests if necessary.TN)r'rJ)rrrr�handle�s	
zBaseHTTPRequestHandler.handleNc
CsLy|j|\}}Wntk
r7d\}}YnX|dkrM|}n|dkrb|}n|jd||�|ji|d6t|�d6t|�d6}|jdd�}|j||�|jd	|j�|jd
d�|jdt	t
|���|j�|jd
krH|dkrH|dkrH|j
j|�ndS)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.

        �???Nzcode %d, message %s�code�message�explainzUTF-8r	zContent-Typer!r#zContent-LengthZHEAD�����0)rLrL)rQrR)�	responses�KeyErrorrG�error_message_formatr
�encode�
send_response�send_header�error_content_typer0r-rAr$rE�write)rrMrNrOZshortmsgZlongmsgZcontentZbodyrrrr.�s&
		(
'z!BaseHTTPRequestHandler.send_errorcCsM|j|�|j||�|jd|j��|jd|j��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@rX�version_string�date_time_string)rrMrNrrrrW�s
z$BaseHTTPRequestHandler.send_responsecCs�|dkr8||jkr/|j|d}q8d}n|jdkr�t|d�sbg|_n|jjd|j||fjdd��ndS)	zSend the response header only.Nrr"zHTTP/0.9�_headers_bufferz
%s %d %s
zlatin-1�strict)rSr&rCr^�appendr2rV)rrMrNrrrr@�s	z)BaseHTTPRequestHandler.send_response_onlycCs�|jdkrSt|d�s*g|_n|jjd||fjdd��n|j�dkr�|j�dkr�d|_q�|j�d	kr�d
|_q�ndS)z)Send a MIME header to the headers buffer.zHTTP/0.9r^z%s: %s
zlatin-1r_Z
connectionr#Tz
keep-aliveFN)r&rCr^r`rVr:r')r�keyword�valuerrrrX�s	 z"BaseHTTPRequestHandler.send_headercCs0|jdkr,|jjd�|j�ndS)z,Send the blank line ending the MIME headers.zHTTP/0.9s
N)r&r^r`�
flush_headers)rrrrrA�sz"BaseHTTPRequestHandler.end_headerscCs;t|d�r7|jjdj|j��g|_ndS)Nr^�)rCrErZ�joinr^)rrrrrc�sz$BaseHTTPRequestHandler.flush_headers�-cCs)|jd|jt|�t|��dS)zNLog an accepted request.

        This is called by send_response().

        z
"%s" %s %sN)�log_messager+r()rrM�sizerrrr[�s	z"BaseHTTPRequestHandler.log_requestcGs|j||�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)rg)r�format�argsrrrrG�sz BaseHTTPRequestHandler.log_errorcGs1tjjd|j�|j�||f�dS)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�stderrrZ�address_string�log_date_time_string)rrirjrrrrgs		z"BaseHTTPRequestHandler.log_messagecCs|jd|jS)z*Return the server software version string.� )�server_version�sys_version)rrrrr\sz%BaseHTTPRequestHandler.version_stringc	Csv|dkrtj�}ntj|�\	}}}}}}}}	}
d|j|||j|||||f}|S)z@Return the current date and time formatted for a message header.Nz#%s, %02d %3s %4d %02d:%02d:%02d GMT)�timeZgmtime�weekdayname�	monthname)rZ	timestamp�year�month�day�hh�mm�ssZwd�y�z�srrrr]"s*
z'BaseHTTPRequestHandler.date_time_stringc	Cs]tj�}tj|�\	}}}}}}}}	}
d||j|||||f}|S)z.Return the current time formatted for logging.z%02d/%3s/%04d %02d:%02d:%02d)rrZ	localtimert)rZnowrurvrwrxryrz�xr{r|r}rrrrn-s
* z+BaseHTTPRequestHandler.log_date_time_stringZMonZTueZWedZThuZFriZSatZSunZJanZFebZMarZAprZMayZJunZJulZAugZSepZOctZNovZDeccCs|jdS)zReturn the client address.r)�client_address)rrrrrm;sz%BaseHTTPRequestHandler.address_stringzHTTP/1.0�Continue�!Request received, please continuer?�Switching Protocols�.Switching to new protocol; obey Upgrade header�e�OK�#Request fulfilled, document followsrP�Created�Document created, URL follows���Accepted�/Request accepted, processing continues off-line���Non-Authoritative Information�Request fulfilled from cache���
No Content�"Request fulfilled, nothing followsrQ�
Reset Content�#Clear input form for further input.���Partial Content�Partial content follows.���Multiple Choices�,Object has several resources -- see URI listi,�Moved Permanently�(Object moved permanently -- see URI listi-�Found�(Object moved temporarily -- see URI listi.�	See Other�'Object moved -- see Method and URL listi/�Not Modified�)Document has not changed since given timei0�	Use Proxy�AYou must use proxy specified in Location to access this resource.i1�Temporary Redirecti3�Bad Request�(Bad request syntax or unsupported methodi��Unauthorized�*No permission -- see authorization schemesi��Payment Required�"No payment -- see charging schemesi��	Forbidden�0Request forbidden -- authorization will not helpi��	Not Found�Nothing matches the given URIi��Method Not Allowed�.Specified method is invalid for this resource.i��Not Acceptable�&URI not available in preferred format.i��Proxy Authentication Required�8You must authenticate with this proxy before proceeding.i��Request Timeout�#Request timed out; try again later.i��Conflict�Request conflict.i��Gone�6URI no longer exists and has been permanently removed.i��Length Required�#Client must specify Content-Length.i��Precondition Failed�!Precondition in headers is false.i��Request Entity Too Large�Entity is too large.i��Request-URI Too Long�URI is too long.i��Unsupported Media Type�"Entity body in unsupported format.i��Requested Range Not Satisfiable�Cannot satisfy request range.i��Expectation Failed�(Expect condition could not be satisfied.i��Precondition Required�9The origin server requires the request to be conditional.i��Too Many Requests�PThe user has sent too many requests in a given amount of time ("rate limiting").i��Request Header Fields Too Large�WThe server is unwilling to process the request because its header fields are too large.i��Internal Server Error�Server got itself in troublei��Not Implemented�&Server does not support this operationi��Bad Gateway�,Invalid responses from another server/proxy.i��Service Unavailable�8The server cannot process the request due to a high loadi��Gateway Timeout�4The gateway server did not receive a timely responsei��HTTP Version Not Supported�Cannot fulfill request.i��Network Authentication Required�8The client needs to authenticate to gain network access.i�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)r�r�)(rrr�__doc__rkr<r,rq�__version__rp�DEFAULT_ERROR_MESSAGErU�DEFAULT_ERROR_CONTENT_TYPErYr%r>r;rJrKr.rWr@rXrArcr[rGrgr\r]rnrsrtrmr2r4r5ZHTTPMessager7rSrrrrr�s�f
Q#'

	c@s�eZdZdZdeZdd�Zdd�Zdd�Zd	d
�Z	dd�Z
d
d�Zdd�Ze
js�e
j�ne
jj�Zejidd6dd6dd6dd6�dS)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/c
Cs>|j�}|r:z|j||j�Wd|j�XndS)zServe a GET request.N)�	send_head�copyfilerEr#)r�frrr�do_GET�s
zSimpleHTTPRequestHandler.do_GETcCs#|j�}|r|j�ndS)zServe a HEAD request.N)r�r#)rr�rrr�do_HEAD�sz SimpleHTTPRequestHandler.do_HEADc	Cs�|j|j�}d}tjj|�r
tjj|j�}|jjd�s�|jd�|d|d|dd|d|df}tjj	|�}|j
d	|�|j�dSxOdD]7}tjj||�}tjj
|�r�|}Pq�q�W|j|�Sn|j|�}yt|d�}Wn&tk
rW|jd
d�dSYnXyz|jd�|j
d|�tj|j��}|j
dt|d��|j
d|j|j��|j�|SWn|j��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.

        Nri-rrrr�ZLocation�
index.html�	index.htm�rbi�zFile not foundrPzContent-typezContent-Length�z
Last-Modified)r�r�)�translate_pathr3�os�isdir�urllib�parseZurlsplit�endswithrWZ
urlunsplitrXrAre�exists�list_directory�
guess_type�open�OSErrorr.�fstat�filenor(r]�st_mtimer#)	rr3r��partsZ	new_partsZnew_url�indexZctypeZfsrrrr��sF



	


z"SimpleHTTPRequestHandler.send_headc
Cs`ytj|�}Wn&tk
r;|jdd�dSYnX|jddd��g}ytjj|jdd�}Wn$t	k
r�tjj|�}YnXt
j|�}tj
�}d	|}|jd
�|jd�|jd|�|jd
|�|jd|�|jd�x�|D]�}tjj||�}|}	}
tjj|�rr|d}	|d}
ntjj|�r�|d}	n|jdtjj|
dd�t
j|	�f�q$W|jd�dj|�j|d�}tj�}|j|�|jd�|jd�|jdd|�|jdtt|���|j�|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().

        i�zNo permission to list directoryN�keycSs
|j�S)N)r:)�arrr�<lambda>�sz9SimpleHTTPRequestHandler.list_directory.<locals>.<lambda>�errors�
surrogatepasszDirectory 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>
�
�surrogateescaperrPzContent-typeztext/html; charset=%szContent-Length)r��listdirr�r.�sortr�r��unquoter3�UnicodeDecodeErrorr
�escaperk�getfilesystemencodingr`rer��islinkZquoterV�io�BytesIOrZ�seekrWrXr(r-rA)
rr3�list�rZdisplaypath�enc�title�name�fullnameZdisplaynameZlinknameZencodedr�rrrr��sX
	




	





	




z'SimpleHTTPRequestHandler.list_directorycCs*|jdd�d}|jdd�d}|j�jd�}ytjj|dd�}Wn$tk
r�tjj|�}YnXtj|�}|jd�}t	d|�}t
j�}xS|D]K}t
jj
|�s�|t
jt
jfkr�q�nt
jj||�}q�W|r&|d7}n|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.)

        �?rr�#rr�r�N)r,r*r�r�r�rr�	posixpath�normpath�filterr��getcwdr3�dirname�curdir�pardirre)rr3Ztrailing_slashr=Zwordrrrr�s$	

*
z'SimpleHTTPRequestHandler.translate_pathcCstj||�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
outputfilerrrr�<sz!SimpleHTTPRequestHandler.copyfilecCsdtj|�\}}||jkr/|j|S|j�}||jkrU|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.

        r"N)r�splitext�extensions_mapr:)rr3�baseZextrrrr�Lsz#SimpleHTTPRequestHandler.guess_typezapplication/octet-streamr"z
text/plainz.pyz.cz.hN)rrrr�r�rpr�r�r�r�r�r�r��	mimetypesZinitedZinitZ	types_map�copyr�updaterrrrr�s"
	18	
	c	Cs7|jd�\}}}tjj|�}|jd�}g}xS|dd�D]A}|dkro|j�qP|rP|dkrP|j|�qPqPW|r�|j�}|r�|dkr�|j�d}q�|dkr�d}q�q�nd}|rdj||f�}nddj|�|f}dj|�}|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.

    rrNrz..r r"���)�	partitionr�r�rr,�popr`re)	r3�_�query�
path_partsZ
head_parts�partZ	tail_partZ	splitpath�collapsed_pathrrr�_url_collapse_pathqs.

	r,cCs�tr
tSyddl}Wntk
r2dSYnXy|jd�daWn5tk
r�dtdd�|j�D��aYnXtS)	z$Internal routine to get nobody's uidrNr�nobodyrcss|]}|dVqdS)rNr)�.0r~rrr�	<genexpr>�sznobody_uid.<locals>.<genexpr>r$)r-�pwd�ImportError�getpwnamrT�maxZgetpwall)r0rrr�
nobody_uid�s
	
(r4cCstj|tj�S)zTest for executable file.)r��access�X_OK)r3rrr�
executable�sr7c@seZdZdZeed�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-|j�r|j�n|jdd�dS)zRServe a POST request.

        This is only implemented for CGI scripts.

        i�zCan only POST to CGI scriptsN)�is_cgi�run_cgir.)rrrr�do_POST�s
zCGIHTTPRequestHandler.do_POSTcCs'|j�r|j�Stj|�SdS)z-Version of send_head that support CGI scriptsN)r9r:rr�)rrrrr��s
zCGIHTTPRequestHandler.send_headcCslt|j�}|jdd�}|d|�||dd�}}||jkrh||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).

        rrNTF)r,r3�find�cgi_directories�cgi_info)rr+Zdir_sep�head�tailrrrr9�s%zCGIHTTPRequestHandler.is_cgiz/cgi-binz/htbincCs
t|�S)z1Test whether argument path is an executable file.)r7)rr3rrr�
is_executable�sz#CGIHTTPRequestHandler.is_executablecCs(tjj|�\}}|j�dkS)z.Test whether argument path is a Python script.�.py�.pyw)rBrC)r�r3rr:)rr3r?r@rrr�	is_python�szCGIHTTPRequestHandler.is_pythonc)Cs�|j\}}|d|}|jdt|�d�}x�|dkr�|d|�}||dd�}|j|�}tjj|�r�||}}|jdt|�d�}q<Pq<W|jd�\}}}	|jd�}|dkr|d|�||d�}
}n
|d}
}|d|
}|j|�}tjj|�si|j	dd|�dStjj
|�s�|j	d	d
|�dS|j|�}
|js�|
r�|j
|�s�|j	d	d|�dSntjtj�}|j�|d<|jj|d
<d|d<|j|d<t|jj�|d<|j|d<tjj|�}||d<|j|�|d<||d<|	r�|	|d<n|jd|d<|jjd�}|r�|j�}t|�dkr�ddl}ddl }|d|d<|dj!�dkr�y/|dj"d�}|j#|�j$d�}Wn|j%t&fk
rcYq�X|jd�}t|�dkr�|d|d<q�q�q�n|jjd�dkr�|jj'�|d <n|jd|d <|jjd!�}|r||d"<n|jjd#�}|r(||d$<ng}xc|jj(d%�D]O}|dd�d&krs|j)|j*��qA||d'd�jd(�}qAWd(j+|�|d)<|jjd*�}|r�||d+<nt,d|jj-d,g��}d-j+|�}|r||d.<nxdCD]}|j.|d�qW|j/d0d1�|j0�|	j1d2d3�}|jr�|
g}d4|kr�|j)|�nt2�}|j3j4�tj5�}|dkr)tj6|d�\}}x<t7j7|j8gggd�dr|j8j9d�s�Pq�q�W|r%|j:d5|�ndSyoytj;|�Wnt<k
rQYnXtj=|j8j>�d�tj=|j3j>�d�tj?|||�Wq�|jj@|jA|j�tjBd6�Yq�XnddlC} |g}!|j|�rBtDjE}"|"j!�jFd7�r/|"ddD�|"dEd�}"n|"d:g|!}!nd4|	kr^|!j)|	�n|jGd;| jH|!��ytI|�}#WntJtKfk
r�d}#YnX| jL|!d<| jMd=| jMd>| jMd?|�}$|jj!�d@kr|#dkr|j8j9|#�}%nd}%xBt7j7|j8jNgggd�drX|j8jNjOd�sPqqW|$jP|%�\}&}'|j3jQ|&�|'r�|j:dA|'�n|$jRjS�|$jTjS�|$jU}(|(r�|j:d5|(�n
|jGdB�dS)FzExecute a CGI script.rrrNrr"i�zNo such CGI script (%r)i�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�
authorizationrZ	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�REMOTE_HOSTrPzScript output follows�+ro�=zCGI script exit status %#x�zw.exerr�z-uzcommand: %s�stdin�stdoutrl�envZpostz%szCGI script exited OK)rErQrIrOrPrK������)Vr>r<r-r�r�r3r�r%r�r.�isfilerD�	have_forkrAr"�deepcopy�environr\Zserverrr2r(rr$r�r�rrr8r9r,�base64�binasciir:rVZdecodebytes�decode�Error�UnicodeErrorZget_content_typeZgetallmatchingheadersr`�striprerZget_all�
setdefaultrWrcr	r4rErFr8�waitpid�selectr6�readrG�setuidr��dup2r��execveZhandle_errorZrequest�_exit�
subprocessrkr7r�rgZlist2cmdliner0�	TypeErrorr/�Popen�PIPEZ_sockZrecvZcommunicaterZrlr#rV�
returncode))r�dir�restr3�iZnextdirZnextrestZ	scriptdirr'r(ZscriptZ
scriptnameZ
scriptfileZispyrWZuqrestrFr^r_ZlengthrJrL�lineZua�coZ
cookie_str�kZ
decoded_queryrjr-�pid�stsrlZcmdlineZinterp�nbytes�p�datarVrlZstatusrrrr:�s,
$









!



			
%
		!				!(

	zCGIHTTPRequestHandler.run_cgiN)rrrr�rCr�r[Zrbufsizer;r�r9r=rArDr:rrrrr�szHTTP/1.0i@r"cCs�||f}||_|||�}|jj�}td|dd|dd�y|j�Wn3tk
r�td�|j�tjd�YnXdS)zmTest the HTTP request handler class.

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

    zServing HTTP onrrrz...z&
Keyboard interrupt received, exiting.N)	r2rr�printZ
serve_forever�KeyboardInterruptZserver_closerk�exit)�HandlerClassZServerClassZprotocolr�bindZserver_addressZhttpdZsarrr�test�s	


r��__main__z--cgi�action�
store_true�helpzRun as CGI Serverz--bindz-b�default�metavarZADDRESSz8Specify alternate bind address [default: all interfaces]rZstore�type�nargsrz&Specify alternate port [default: 8000]rr�)-r�r��__all__r
Zhttp.clientr4r
r!r�rrfrrrrkrrZurllib.parser�r"�argparser�r�r
rrZStreamRequestHandlerrrr,r-r4r7rr�r�ArgumentParser�parser�add_argumentr0�
parse_argsrjZcgiZ
handler_classrr�rrrr�<module> sb3���0�