HEX
Server: LiteSpeed
System: Linux s787.bom1.mysecurecloudhost.com 4.18.0-477.13.1.lve.el8.x86_64 #1 SMP Thu Jun 1 16:40:47 EDT 2023 x86_64
User: mobilech (5348)
PHP: 8.1.34
Disabled: NONE
Upload Files
File: //opt/saltstack/salt/lib/python3.10/site-packages/cheroot/__pycache__/server.cpython-310.pyc
o

;jL9�@s|dZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlmZddlmZmZmZddlmZmZddlmZmZddlmZd	Z e�!�d
kZ"	e�#dd��$d
�Z%	e"oxe%Z&	e&r�z
ddl'Z'ddl(Z(Wne)y�	dZ&d\Z'Z(Ynwddl*Z*nd\Z'Z(Z*e"r�e+e
d�r�e+e
d�s�de
_,e+e
d�s�de
_-e+e
d�s�	er�dnde
_.dZ/dZ0dZ1dZ2dZ3dZ4dZ5d Z6d!Z7d"Z8e	�9d�:d#e8f��Z;e<�Z=gd$�Z>e+ed%�s�ie_?Gd&d'�d'�Z@Gd(d)�d)e@�ZAGd*d+�d+�ZBGd,d-�d-�ZCGd.d/�d/�ZDGd0d1�d1�ZEGd2d3�d3�ZFGd4d5�d5�ZGGd6d7�d7�ZHd8d9d:�ZId>d<d=�ZJdS)?a�
A high-speed, production ready, thread pooled, generic HTTP server.

For those of you wanting to understand internals of this module, here's the
basic call flow. The server's listening thread runs a very tight loop,
sticking incoming connections onto a Queue::

    server = HTTPServer(...)
    server.start()
    ->  serve()
        while ready:
            _connections.run()
                while not stop_requested:
                    child = socket.accept()  # blocks until a request comes in
                    conn = HTTPConnection(child, ...)
                    server.process_conn(conn)  # adds conn to threadpool

Worker threads are kept in a pool and poll the Queue, popping off and then
handling each connection in turn. Each connection can consist of an arbitrary
number of requests and their responses, so we run a nested loop::

    while True:
        conn = server.requests.get()
        conn.communicate()
        ->  while True:
                req = HTTPRequest(...)
                req.parse_request()
                ->  # Read the Request-Line, e.g. "GET /page HTTP/1.1"
                    req.rfile.readline()
                    read_headers(req.rfile, req.inheaders)
                req.respond()
                ->  response = app(...)
                    try:
                        for chunk in response:
                            if chunk:
                                req.write(chunk)
                    finally:
                        if hasattr(response, "close"):
                            response.close()
                if req.close_connection:
                    return

For running a server you can invoke :func:`start() <HTTPServer.start()>` (it
will run the server forever) or use invoking :func:`prepare()
<HTTPServer.prepare()>` and :func:`serve() <HTTPServer.serve()>` like this::

    server = HTTPServer(...)
    server.prepare()
    try:
        threading.Thread(target=server.serve).start()

        # waiting/detecting some appropriate stop condition here
        ...

    finally:
        server.stop()

And now for a trivial doctest to exercise the test suite

.. testsetup::

   from cheroot.server import HTTPServer

>>> 'HTTPServer' in globals()
True
�N)�	lru_cache�)�__version__�connections�errors)�IS_PPC�bton)�MakeFile�StreamWriter)�
threadpool)
�ChunkedRFile�DropUnderscoreHeaderReader�Gateway�HTTPConnection�HTTPRequest�
HTTPServer�HeaderReader�KnownLengthRFile�SizeCheckWrapper�get_ssl_adapter_class�WindowsZSERVER_SOFTWARE�zGoogle App Engine/F)NN)NNN�AF_INET6�IPPROTO_IPV6�)�IPV6_V6ONLY��SO_PEERCRED���
s
�	� �:�;��*�/s%2Fs(?i))sAcceptsAccept-CharsetsAccept-EncodingsAccept-Languages
Accept-RangessAllows
Cache-Control�
ConnectionsContent-EncodingsContent-Language�ExpectsIf-Matchs
If-None-MatchsPragmasProxy-AuthenticatesTEsTrailer�Transfer-EncodingsUpgradesVarysViasWarningsWWW-Authenticate�
statisticsc@s*eZdZdZd	dd�Zdd�Zdd�ZdS)
rz`Object for reading headers from an HTTP request.

    Interface and default implementation.
    NcCs�|duri}d}	|��}|std��|tkr	|S|�t�s#td��|dd�tthvr2|��}n!z
|�td�\}}WntyGtd��w|��}|�	|�}|}|�
|�sYq|tvrk|�|�}|rkd�
||f�}|||<q	)a�
        Read headers from the given stream into the given header dict.

        If hdict is None, a new header dict is created. Returns the populated
        header dict.

        Headers which are repeated are folded together using a comma if their
        specification so dictates.

        This function raises ValueError when the read bytes violate the HTTP
        spec.
        You should probably return "400 Bad Request" if this happens.
        NT�Illegal end of headers.�HTTP requires CRLF terminatorsrzIllegal header line.s, )�readline�
ValueError�CRLF�endswith�SPACE�TAB�strip�split�COLON�_transform_key�
_allow_header�comma_separated_headers�get�join)�self�rfileZhdict�hname�line�v�k�existing�rC�B/opt/saltstack/salt/lib/python3.10/site-packages/cheroot/server.py�__call__�s<
�
�


�zHeaderReader.__call__cCsdS)NTrC�r<�key_namerCrCrDr8szHeaderReader._allow_headercCs|����S�N)r4�titlerFrCrCrDr7
szHeaderReader._transform_keyrH)�__name__�
__module__�__qualname__�__doc__rEr8r7rCrCrCrDr�s

9rcs eZdZdZ�fdd�Z�ZS)r
zDCustom HeaderReader to exclude any headers with underscores in them.cstt|��|�}|o
d|vS)N�_)�superr
r8)r<rG�orig��	__class__rCrDr8sz(DropUnderscoreHeaderReader._allow_header)rJrKrLrMr8�
__classcell__rCrCrQrDr
sr
c@sZeZdZdZdd�Zdd�Zddd�Zdd	d
�Zddd
�Zdd�Z	dd�Z
dd�ZeZdS)rz�Wraps a file-like object, raising MaxSizeExceeded if too large.

    :param rfile: ``file`` of a limited size
    :param int maxlen: maximum length of the file being read
    cCs||_||_d|_dS)z%Initialize SizeCheckWrapper instance.rN)r=�maxlen�
bytes_read)r<r=rTrCrCrD�__init__s
zSizeCheckWrapper.__init__cCs |jr|j|jkrtj�dSdSrH)rTrUr�MaxSizeExceeded�r<rCrCrD�
_check_length$s�zSizeCheckWrapper._check_lengthNcCs*|j�|�}|jt|�7_|��|S)��Read a chunk from ``rfile`` buffer and return it.

        :param size: amount of data to read
        :type size: int

        :returns: chunk from ``rfile``, limited by size if specified
        :rtype: bytes
        )r=�readrU�lenrY�r<�size�datarCrCrDr[(s	zSizeCheckWrapper.readcCs�|dur|j�|�}|jt|�7_|��|Sg}	|j�d�}|jt|�7_|��|�|�t|�dksB|dd�tkrGt�|�Sq)��Read a single line from ``rfile`` buffer and return it.

        :param size: minimum amount of data to read
        :type size: int

        :returns: one line from ``rfile``
        :rtype: bytes
        NT����)	r=r.rUr\rY�append�LF�EMPTYr;)r<r^r_�resrCrCrDr.6s	

�zSizeCheckWrapper.readlinercC�Xd}g}|�|�}|r*|�|�|t|�7}d|kr"|kr#	|S|�|�}|s|S�z�Read all lines from ``rfile`` buffer and return them.

        :param sizehint: hint of minimum amount of data to read
        :type sizehint: int

        :returns: lines of bytes read from ``rfile``
        :rtype: list[bytes]
        r�r.rcr\�r<�sizehint�total�linesr?rCrCrD�	readlinesQ�


�
�zSizeCheckWrapper.readlinescC�|j��dS�z*Release resources allocated for ``rfile``.N�r=�closerXrCrCrDrsf�zSizeCheckWrapper.closecC�|S�zReturn file iterator.rCrXrCrCrD�__iter__j�zSizeCheckWrapper.__iter__cCs(t|j�}|jt|�7_|��|S�zGenerate next file chunk.)�nextr=rUr\rY�r<r_rCrCrD�__next__ns
zSizeCheckWrapper.__next__rH�r)
rJrKrLrMrVrYr[r.rnrsrwr|rzrCrCrCrDrs


rc@sReZdZdZdd�Zddd�Zddd�Zdd
d�Zdd
�Zdd�Z	dd�Z
e
ZdS)rz�Wraps a file-like object, returning an empty string when exhausted.

    :param rfile: ``file`` of a known size
    :param int content_length: length of the file being read
    cCs||_||_dS)z%Initialize KnownLengthRFile instance.N)r=�	remaining)r<r=�content_lengthrCrCrDrVs
zKnownLengthRFile.__init__NcC�L|jdkrdS|dur|j}nt||j�}|j�|�}|jt|�8_|S)z�Read a chunk from ``rfile`` buffer and return it.

        :param size: amount of data to read
        :type size: int

        :rtype: bytes
        :returns: chunk from ``rfile``, limited by size if specified
        rr%N)r~�minr=r[r\r]rCrCrDr[��
	zKnownLengthRFile.readcCr�)r`rr%N)r~r�r=r.r\r]rCrCrDr.�r�zKnownLengthRFile.readlinercCrgrhrirjrCrCrDrn�rozKnownLengthRFile.readlinescCrprqrrrXrCrCrDrs�rtzKnownLengthRFile.closecCrurvrCrXrCrCrDrw�rxzKnownLengthRFile.__iter__cCs t|j�}|jt|�8_|Sry)rzr=r~r\r{rCrCrDr|�s
zKnownLengthRFile.__next__rHr})rJrKrLrMrVr[r.rnrsrwr|rzrCrCrCrDrxs


rc@sPeZdZdZddd�Zdd�Zddd	�Zdd
d�Zdd
d�Zdd�Z	dd�Z
dS)ra�Wraps a file-like object, returning an empty string when exhausted.

    This class is intended to provide a conforming wsgi.input value for
    request entities that have been encoded with the 'chunked' transfer
    encoding.

    :param rfile: file encoded with the 'chunked' transfer encoding
    :param int maxlen: maximum length of the file being read
    :param int bufsize: size of the buffer used to read the file
    � cCs(||_||_d|_t|_||_d|_dS)z!Initialize ChunkedRFile instance.rFN)r=rTrUre�buffer�bufsize�closed)r<r=rTr�rCrCrDrV�s
zChunkedRFile.__init__cCs|jrdS|j��}|jt|�7_|jr#|j|jkr#t�d|j��|���	t
d�}z|�d�}t|d�}Wnt
yEt
d|����w|dkrOd|_dS|jr^|j||jkr^td��|j�|�}|jt|�7_|j|7_|j�d�}|tkr�t
dt|�d	��dS)
N�Request Entity Too Largerr�zBad chunked transfer size: T�z2Bad chunked transfer coding (expected '\r\n', got �))r�r=r.rUr\rTrrWr4r5�	SEMICOLON�pop�intr/�IOErrorr[r�r0�repr)r<r?Z
chunk_size�chunkZcrlfrCrCrD�_fetch�sH
�
������zChunkedRFile._fetchNcCs�t}|dkr|S	|rt|�|kr|S|js|��|js|S|r9|t|�}||jd|�7}|j|d�|_n||j7}t|_q	)rZrTN)rer\r�r�)r<r^r_r~rCrCrDr[s"	
�zChunkedRFile.readcCs�t}|dkr|S	|rt|�|kr|S|js|��|js|S|j�t�}|r^|dkrC|t|�}||jd|�7}|j|d�|_n9t|t|�|�}||jd|�7}|j|d�|_n|dkrk||j7}t|_n||jd|�7}|j|d�|_q	)r`rTrbN)rer\r�r��findrdr�)r<r^r_Znewline_posr~rCrCrDr.2s2	
�zChunkedRFile.readlinercCrgrhrirjrCrCrDrn[rozChunkedRFile.readlinesccsz�|jstd��	|j��}|std��|jt|�7_|jr*|j|jkr*td��|tkr0dS|�	t�s9td��|Vq	)zhRead HTTP headers and yield them.

        :yields: CRLF separated lines
        :ytype: bytes

        z:Cannot read trailers until the request body has been read.Tr,r�r-N)
r�r/r=r.rUr\rTr�r0r1)r<r?rCrCrD�read_trailer_linesps$��

�zChunkedRFile.read_trailer_linescCrprqrrrXrCrCrDrs�rtzChunkedRFile.close)r�rHr})rJrKrLrMrVr�r[r.rnr�rsrCrCrCrDr�s
	
+
 
)rc@s�eZdZdZdZ	dZ	iZ	gZ	dZ	dZ		dZ
	e�Z	ddd�Z
dd�Zd	d
�Zdd�Zd
d�Zddd�Zdd�Zdd�Zdd�ZdS)rzrAn HTTP Request (and response).

    A single HTTP connection may consist of multiple request/response pairs.
    NFTcCsx||_||_d|_d|_d|_|jjdurd|_d|_i|_d|_g|_	d|_
|jj|_d|_
|jj|_||_||_dS)aInitialize HTTP request container instance.

        Args:
            server (HTTPServer): web server object receiving this request
            conn (HTTPConnection): HTTP connection object for this request
            proxy_mode (bool): whether this HTTPServer should behave as a PROXY
            server for certain requests
            strict_mode (bool): whether we should return a 400 Bad Request when
            we encounter a request that a HTTP compliant client should not be
            making
        FshttpNshttpszHTTP/1.0r)�server�conn�ready�started_request�scheme�ssl_adapter�response_protocol�	inheaders�status�
outheaders�sent_headersrR�close_connection�chunked_read�
chunked_write�
proxy_mode�strict_mode)r<r�r�r�r�rCrCrDrV�s"


zHTTPRequest.__init__cCs�t|jj|jj�|_z|��}Wntjy!|�dd�YdSw|s&dSz|�	�}Wntjy=|�dd�YdSw|sBdSd|_
dS)z;Parse the next HTTP request start-line and message-headers.z414 Request-URI Too LongzHThe Request-URI sent with the request exceeds the maximum allowed bytes.N�413 Request Entity Too LargezCThe headers sent with the request exceed the maximum allowed bytes.T)rr�r=r��max_request_header_size�read_request_linerrW�simple_response�read_request_headersr�)r<�successrCrCrD�
parse_request�s6�����
zHTTPRequest.parse_requestc
Cs�|j��}d|_|sdS|tkr|j��}|sdS|�t�s&|�dd�dSzH|���td�\}}}|�	d�s@|�dd�WdS|dd	��d
d�}t
|�dkrY|�dd�WdSttt
|��}|d
krm|�dd�WdSWnttfy�|�dd�YdSw||_|��|_|jr�||jkr�d}|�d|�dSz
tj�|�\}}}	}
}Wnty�|�dd�YdSw|p�|}|jdkr�|jr�|r�|n|	}	n�|jdk�r0|js�|�d�dStj�d�d|f��}
|
\}}}}}t}t�t��|
j}Wd	�n	1�swY||k�p|�pt||||f�}|�r%|�dd�dS|}}	t}}
}nz|j�o:|j�o:|}|�rG	|�dd�dS|j�oT|�	t��oT|}|�rc	d}|�d|�dS|�rn|�dd�dS|	d	u�r{|�dd�dSzdd�t �|	�D�}Wnt�y�}z|�d|j!d�WYd	}~dSd	}~wwt"�|�}	|	�	t��s�t|	}	|tu�r�||_#||_$|	|_%|
|_&t
|j'j(d�t
|j'j(d �f}|d|dk�r�|�d�dS||_)d!t*||�|_+dS)"z�Read and parse first line of the HTTP request.

        Returns:
            bool: True if the request line is valid or False if it's malformed.

        TF�400 Bad Requestr-r�sHTTP/z$Malformed Request-Line: bad protocol�N�.rz#Malformed Request-Line: bad version)rrz505 HTTP Version Not SupportedzCannot fulfill requestzMalformed Request-Linez�Malformed method name: According to RFC 2616 (section 5.1.1) and its successors RFC 7230 (section 3.1.1) and RFC 7231 (section 4.1) method names are case-sensitive and uppercase.zMalformed Request-URIsOPTIONSsCONNECTz405 Method Not Allowedr%s//zFInvalid path in Request-URI: request-target must match authority-form.z2Absolute URI not allowed if server is not a proxy.z�Invalid path in Request-URI: request-target must contain origin-form which starts with absolute-path (URI starting with a slash "/").z!Illegal #fragment in Request-URI.zInvalid path in Request-URI.cSsg|]}tj�|��qSrC)�urllib�parse�unquote_to_bytes��.0�xrCrCrD�
<listcomp>�s
��z1HTTPRequest.read_request_line.<locals>.<listcomp>r�z
HTTP/%s.%s),r=r.r�r0r1r�r4r5r2�
startswithr\�tuple�mapr�r/�
IndexError�uri�upper�methodr�r�r��urlsplit�UnicodeErrorr�r;re�
contextlib�suppress�port�any�
FORWARD_SLASH�QUOTED_SLASH_REGEX�args�QUOTED_SLASHr��	authority�path�qsr��protocolZrequest_protocolr�r�)r<Zrequest_liner�r�Zreq_protocolZrpZrespr�r�r�r��fragmentZuri_is_absolute_formZ	uri_splitZ_schemeZ
_authority�_pathZ_qsZ	_fragmentZ_portZinvalid_pathZdisallowed_absoluteZatoms�ex�sprCrCrDr��s 


�
�����
��
���
�
������
����
�

���

 
zHTTPRequest.read_request_linec
Cs�z
|�|j|j�Wnty&}z|�d|jd�WYd}~dSd}~ww|jj}zt|j�	dd��}WntyF|�dd�YdSw|rU||krU|�dd�dS|j
d	krg|j�	d
d�dkrfd
|_n|j�	d
d�dkrsd
|_d}|j
d	kr�|j�	d�}|r�dd�|�d�D�}d|_
|r�|D]}|dkr�d
|_
q�|�d�d
|_dS|j�	dd�dkr�d�|jj�d�tdttf�}z
|jj�|�Wd
Stjy�}z|jdtjvr܂WYd}~d
Sd}~wwd
S)z�Read ``self.rfile`` into ``self.inheaders``.

        Ref: :py:attr:`self.inheaders <HTTPRequest.outheaders>`.

        :returns: success status
        :rtype: bool
        r�rNF�Content-Lengthz Malformed Content-Length Header.r��CThe entity sent with the request exceeds the maximum allowed bytes.�HTTP/1.1r(r%�closeT�
Keep-Aliver*cSs g|]}|��r|�����qSrC)r4�lowerr�rCrCrDr�s z4HTTPRequest.read_request_headers.<locals>.<listcomp>�,�chunkedz501 Unimplementedr)s100-continue�asciis100 Continue)�
header_readerr=r�r/r�r�r��max_request_body_sizer�r:r�r�r5r�r;r��encoder2r0r��wfile�write�socket�errorr�socket_errors_to_ignore)r<r��mrbs�cl�te�enc�msgrCrCrDr��s|	�����
�

��	�
���z HTTPRequest.read_request_headerscCs�|jj}|jrt|jj|�|_n"t|j�dd��}|r*||kr*|j	s(|�
dd�dSt|jj|�|_|j�|��
�|jo@|��|jrM|jj�d�dSdS)z/Call the gateway and write its iterable output.r�rr�r�Ns0

)r�r�r�rr�r=r�r�r:r�r�r�gateway�respondr��ensure_headers_sentr�r�r�)r<r�r�rCrCrDr�Es$���zHTTPRequest.respondrc
Cs�t|�}d|jj|f}dt|�}d}|�d�|�d�|�d�g}|dd�dvr:d|_|jd	kr8|�d
�nd}|�t�|rPt	|t�rK|�d�}|�|�z
|j
j�t
�|��WdStjyz}z|jdtjvro�WYd}~dSd}~ww)
z+Write a simple response back to the client.z%s %s
zContent-Length: %s
zContent-Type: text/plain
�
ISO-8859-1N�>Z413Z414Tr�sConnection: close
r�r)�strr�r�r\r�r�r�rcr0�
isinstancer�r�r�rer;r�r�r�rr�)r<r�r�Zproto_statusr�content_type�bufr�rCrCrDr�\s4�




���zHTTPRequest.simple_responsecCs|jsd|_|��dSdS)z:Ensure headers are sent to the client if not already sent.TN)r��send_headersrXrCrCrDr��s�zHTTPRequest.ensure_headers_sentcCsZ|jr$|r$tt|��dd��d�}|t|tg}|jj�t�	|��dS|jj�|�dS)z$Write unbuffered data to the client.r�Nr�)
r��hexr\r�r0r�r�r�rer;)r<r�Zchunk_size_hexr�rCrCrDr��s

zHTTPRequest.writec
Cs�dd�|jD�}t|jdd��}|dkrd|_n&d|vr?|dks%|d	vr&n|jd
ko/|jdk}|r<d|_|j�d�nd|_|jsJ|jj	}||_d
|vrf|jd
kr]|jr\|j�d�n	|jsf|j�d�d|jvr{|j�dd|jj
���d�f�|js�|js�t
|jdd�}|dkr�|j�|�d|vr�|j�dtjjdd��d�f�d|vr�|j�d|jj�d�f�|jj�d�}|t|jtg}|jD]\}}	|�|tt|	t�q�|�t�|jj�t�|��dS)z�Assert, process, and send the HTTP response message-headers.

        You must set ``self.status``, and :py:attr:`self.outheaders
        <HTTPRequest.outheaders>` before calling this.
        cSsg|]\}}|���qSrC)r�)r��key�valuerCrCrDr��sz,HTTPRequest.send_headers.<locals>.<listcomp>Nr�i�Tscontent-length��>i0����r�sHEAD)r*r�s
connection)r(r�)r(r�r�ztimeout=r�r~rsdatesDate)�usegmtsserversServerr�)r�r�r�r�r�r�r�rcr��can_add_keepalive_connection�timeoutr�r��getattrr=r[�email�utils�
formatdate�server_namer�r2r0r6r�r�r�rer;)
r<Zhkeysr�Z
needs_chunkedZcan_keepr~�protor�rAr@rCrCrDr��sh
�
�
��
����
zHTTPRequest.send_headers)FT)r)rJrKrLrMr�r�r�r�r�r�r�rr�rVr�r�r�r�r�r�r�r�rCrCrCrDr�s8
!"fd
%	rc@s�eZdZdZdZdZdZejZ	ejZ
eZdZ
dZdZefdd�Zdd�ZdZdd	�Zd
d�Zdd
�Zdd�Zedd��Zedd��Zedd��Zdd�Zedd��Zedd��Zdd�ZdS)rz#An HTTP connection (active socket).NFcCsn||_||_||d|j�|_||d|j�|_d|_|jj|_|jj|_t	dd�|j
�|_
t	dd�|j�|_dS)aBInitialize HTTPConnection instance.

        Args:
            server (HTTPServer): web server object receiving this request
            sock (socket._socketobject): the raw socket object (usually
                TCP) for this connection
            makefile (file): a fileobject class for reading from the socket
        �rb�wbrr)�maxsizeN)r�r��rbufsizer=�wbufsizer��
requests_seen�peercreds_enabled�peercreds_resolve_enabledr�resolve_peer_creds�get_peer_creds)r<r��sock�makefilerCrCrDrV�s	

zHTTPConnection.__init__c
Cs�d}z-|�|j|�}|��|jjdr|jd7_|js!WdSd}|��|js-WdSWdStj	y�}zG|j
d}d}||vrQ|rJ|rP|jrP|�|d�n'|t
jvrq|jjdt|�tjdd	�|�|d
�WYd}~dSWYd}~dSWYd}~dSd}~wttfy��t
jy�YdSt
jy�|�|�YdSty�}z|jjt|�tjdd	�|�|d
�WYd}~dSd}~ww)zrRead each request and respond appropriately.

        Returns true if the connection should be kept open.
        F�EnabledrTr)z	timed outzThe read operation timed outz408 Request Timeoutzsocket.error %s��level�	tracebackz500 Internal Server ErrorN)�RequestHandlerClassr�r��statsrr�r�r�r�r�r�r��_conditional_errorrr��	error_logr��logging�WARNING�KeyboardInterrupt�
SystemExit�
FatalSSLAlert�
NoSSLError�_handle_no_ssl�	Exception�ERROR)r<Zrequest_seen�reqr�ZerrnumZtimeout_errsrCrCrD�communicatesh�!�
�

�
�
���
�����zHTTPConnection.communicatecCs`|r|jrdSz|jj}Wn
ty|jj}Ynwt|d|j�|_d}|�d|�d|_	dS)Nr�zUThe client sent a plain HTTP request, but this server only speaks HTTPS on this port.r�T)
r�r��_sock�AttributeError�_socketr
rr�r��linger)r<rZ	resp_sockr�rCrCrDrMs
��
zHTTPConnection._handle_no_sslcCsT|r|jrdSz|�|�WdStjyYdStjy)|�|�YdSw)zvRespond with an error.

        Don't bother writing if a response
        has already started being written.
        N)r�r�rrrr)r<r�responserCrCrDr^s
�z!HTTPConnection._conditional_errorcCs,|j��|js|��|j��dS	dS)z,Close the socket underlying this connection.N)r=rsr �_close_kernel_socketr�rXrCrCrDrsns

zHTTPConnection.closec
Cs�d}ts|jjtjkrtd��|jstd��z|j�tjtj	t
�|��}Wntjy6}z	t|�d}~wwt
�
||�\}}}|||fS)a�Return the PID/UID/GID tuple of the peer socket for UNIX sockets.

        This function uses SO_PEERCRED to query the UNIX PID, UID, GID
        of the peer, which is only available if the bind address is
        a UNIX domain socket.

        Raises:
            NotImplementedError: in case of unsupported socket type
            RuntimeError: in case of SO_PEERCRED lookup unsupported or disabled

        Z3iz5SO_PEERCRED is only supported in Linux kernel and WSLz0Peer creds lookup is disabled within this serverN)�
IS_WINDOWSr��family�AF_UNIX�NotImplementedErrorr�RuntimeError�
getsockopt�
SOL_SOCKETr�struct�calcsizer��unpack)r<ZPEERCRED_STRUCT_DEFZ
peer_credsZ
socket_err�pid�uid�gidrCrCrDr�s,�����

zHTTPConnection.get_peer_credscCs|��\}}}|S)z,Return the id of the connected peer process.�r)r<r-rNrCrCrD�peer_pid��zHTTPConnection.peer_pidcCs|��\}}}|S)z1Return the user id of the connected peer process.r0)r<rNr.rCrCrD�peer_uid�r2zHTTPConnection.peer_uidcCs|��\}}}|S)z2Return the group id of the connected peer process.r0)r<rNr/rCrCrD�peer_gid�r2zHTTPConnection.peer_gidcCs>tstd��|js
td��t�|j�j}t�	|j
�j}||fS)aLook up the username and group tuple of the ``PEERCREDS``.

        :returns: the username and group tuple of the ``PEERCREDS``

        :raises NotImplementedError: if the OS is unsupported
        :raises RuntimeError: if UID/GID lookup is unsupported or disabled
        z�UID/GID lookup is unavailable under current platform. It can only be done under UNIX-like OS but not under the Google App Enginez-UID/GID lookup is disabled within this server)�IS_UID_GID_RESOLVABLEr&rr'�pwd�getpwuidr3�pw_name�grp�getgrgidr4�gr_name)r<�user�grouprCrCrDr�s��z!HTTPConnection.resolve_peer_credscCs|��\}}|S)z2Return the username of the connected peer process.�r)r<r<rNrCrCrD�	peer_user��zHTTPConnection.peer_usercCs|��\}}|S)z/Return the group of the connected peer process.r>)r<rNr=rCrCrD�
peer_group�r@zHTTPConnection.peer_groupc
Csnt|jd|jj�}z|tj�WdStjyYdStjy6}z|jtjvr+�WYd}~dSd}~ww)z0Terminate the connection at the transport level.Z
sock_shutdownN)	r�r��shutdown�	SHUT_RDWRrZ#acceptable_sock_shutdown_exceptionsr��errnoZ$acceptable_sock_shutdown_error_codes)r<rB�erCrCrDr"�s����z#HTTPConnection._close_kernel_socket) rJrKrLrMZremote_addrZremote_portZssl_env�io�DEFAULT_BUFFER_SIZErrrrrrZ	last_usedr	rVrr rrrsr�propertyr1r3r4rr?rAr"rCrCrCrDr�s<6,




rc@s�eZdZdZdZdZdZ	dZ	dZ	dZ		dZ
	dZ	dZ	dZ
	dZ	de��Z	dZ	d	Z	d
Z	d
Z	dZ	eZ	dZ	d	Z	d	Z	d	Z	dZ										dAd
d�Zdd�Zdd�Zdd�Z e!dd��Z"e"j#dd��Z"dd�Z$dd�Z%dd�Z&dd�Z'd d!�Z(e)j*d"d#��Z+e!d$d%��Z,d&d'�Z-dBd*d+�Z.dCd,d-�Z/d.d/�Z0e1d0d1��Z2e3		dDd2d3��Z4e1d4d5��Z5e1d6d7��Z6d8d9�Z7e!d:d;��Z8e!d<d=��Z9e8j#d>d;��Z8d?d@�Z:dS)ErzAn HTTP server.z	127.0.0.1Nr�r��
g�?zCheroot/FrTrbc		Cs^||_||_tj||pd|d�|_|s|j}||_||_|o||_||_	|�
�t��|_
dS)aInitialize HTTPServer instance.

        Args:
            bind_addr (tuple): network interface to listen to
            gateway (Gateway): gateway for processing HTTP requests
            minthreads (int): minimum number of threads for HTTP thread pool
            maxthreads (int): maximum number of threads for HTTP thread pool
            server_name (str): web server name to be advertised via Server
                HTTP header
            reuse_port (bool): if True SO_REUSEPORT option would be set to
                socket
        r)r��maxN)�	bind_addrr�rZ
ThreadPool�requests�versionr�rr�
reuse_port�clear_stats�queue�Queue�_unservicable_conns)	r<rKr��
minthreads�
maxthreadsr�rrrNrCrCrDrVUs ��zHTTPServer.__init__cs�d�_d�_idd�d�fdd��d�fd	d��d
d�d�fdd��d
�fdd��d�fdd��d�fdd��dd�ddd��ddd��ddd��ddd��ddd��ddd��d i��_�jtjd!t��<dS)"zReset server stat counters..Nrr
FzBind Addresscs
t�j�SrH)r�rK��srXrCrD�<lambda>�s
z(HTTPServer.clear_stats.<locals>.<lambda>zRun timecs|drdp
���S)Nr
rb��runtimerUrXrCrDrW�s�AcceptszAccepts/seccs|d���S)NrZrXrUrXrCrDrW�srQc�t�jdd�S)N�qsize�r�rLrUrXrCrDrW��ZThreadscstt�jdg��S)NZ_threads)r\r�rLrUrXrCrDrW�szThreads Idlecr[)NZidler]rUrXrCrDrW�r^z
Socket Errors�RequestscS�*|drdptdd�|d��D�d�S)Nr
rbcs��|]	}|d|�VqdS)r_NrC�r��wrCrCrD�	<genexpr>����;HTTPServer.clear_stats.<locals>.<lambda>.<locals>.<genexpr>�Worker Threadsr��sum�valuesrUrCrCrDrW��
��
Bytes ReadcSr`)Nr
rbcsra)rlNrCrbrCrCrDrd�rerfrgrrhrUrCrCrDrW�rk�
Bytes WrittencSr`)Nr
rbcsra)rmNrCrbrCrCrDrd�rerfrgrrhrUrCrCrDrW�rk�	Work TimecSr`)Nr
rbcsra)rnNrCrbrCrCrDrd�rerfrgrrhrUrCrCrDrW�rkzRead ThroughputcSr`)Nr
rbcs�,�|]}|d|�|d|�pdVqdS)rlrn���ư>NrCrbrCrCrDrd��
��
�rfrgrrhrUrCrCrDrW��
��zWrite ThroughputcSr`)Nr
rbcsro)rmrnrpNrCrbrCrCrDrd�rqrfrgrrhrUrCrCrDrW�rrrgzCheroot HTTPServer %d)�_start_time�	_run_timerrr+�idrXrCrXrDrO�sH�������	�
������'�/�1zHTTPServer.clear_statscCs$|jdur|jS|jt��|jS)zReturn server uptime.N)rsrt�timerXrCrCrDrY�s
zHTTPServer.runtimecCsd|j|jj|jfS)z1Render Server instance representing bind address.z	%s.%s(%r))rKrRrJrKrXrCrCrD�__str__�s
�zHTTPServer.__str__cC�|jS)a�Return the interface on which to listen for connections.

        For TCP sockets, a (host, port) tuple. Host values may be any
        :term:`IPv4` or :term:`IPv6` address, or any valid hostname.
        The string 'localhost' is a synonym for '127.0.0.1' (or '::1',
        if your hosts file prefers :term:`IPv6`).
        The string '0.0.0.0' is a special :term:`IPv4` entry meaning
        "any active interface" (INADDR_ANY), and '::' is the similar
        IN6ADDR_ANY for :term:`IPv6`.
        The empty string or :py:data:`None` are not allowed.

        For UNIX sockets, supply the file name as a string.

        Systemd socket activation is automatic and doesn't require tempering
        with this variable.

        .. glossary::

           :abbr:`IPv4 (Internet Protocol version 4)`
              Internet Protocol version 4

           :abbr:`IPv6 (Internet Protocol version 6)`
              Internet Protocol version 6
        )�
_bind_addrrXrCrCrDrK�szHTTPServer.bind_addrcCs(t|t�r|ddvrtd��||_dS)z5Set the interface on which to listen for connections.r>rNzzHost values of '' or None are not allowed. Use '0.0.0.0' (IPv4) or '::' (IPv6) instead to listen on all active interfaces.N)r�r�r/ry)r<r�rCrCrDrK�s
�
c
Csjz|��WdSty}z|j}|s||_||�d}~wty4}z|j}|s-||_||�d}~ww)z4Run the server forever, and stop it cleanly on exit.N)�startr�	interruptr)r<Zkb_intr_excZunderlying_interruptZsys_exit_excrCrCrD�
safe_start�s���zHTTPServer.safe_startcCs�d|_|jdurd|j|_d|_d}t�dd�r$t�dtjtj�|_n�t	|j
ttf�rPz|�
|j
�Wn�tjyO}zd||j
|f}t�|�|�d}~ww|j
\}}zt�||tjtjdtj�}Wn$tjy�tj}|j
}d|vr}tj}|d	}|tjdd
|fg}Ynw|D]8}|\}	}
}}}
z
|�|	|
|�Wn%tjy�}zd||
|f}|jr�|j��d|_WYd}~q�d}~ww|js�t�|��|j�d�|j�|j�t�|�|_|j��d|_t��|_ dS)
z�Prepare server to serving requests.

        It binds a socket's port, setups the socket to ``listen()`` and does
        other preparing things.
        Nz	%s ServerzNo socket could be createdZ
LISTEN_PIDr�z%s -- (%s: %s)r�:)rrrrT)!�
_interrupt�softwarerMr��os�getenv�fromfd�AF_INET�SOCK_STREAMr�rKr��bytes�bind_unix_socketr��getaddrinfo�	AF_UNSPEC�
AI_PASSIVE�gaierrorr�bindrs�
settimeout�listen�request_queue_sizerZConnectionManager�_connectionsrLrzr�rvrs)r<r�Zserr�hostr��infoZ	sock_typerKrf�af�socktyper��
_canonname�sarCrCrD�preparesj
��
��

��

zHTTPServer.preparec
Cs�|jrP|j��}|turdSt||�}z|�d�Wn)ttjfy&Yqt	yC}z|j
jt|�t
jdd�WYd}~nd}~wwd|_|��|jsdSdS)z(Serve connections we can't handle a 503.Nz503 Service UnavailableTr)r�rRr:�_STOPPING_FOR_INTERRUPTrr��OSErrorrrrr�rr�rrr rs)r<r��requestr�rCrCrD�_serve_unservicableQs(

���	�zHTTPServer._serve_unservicablec	Cs�tj|jd���|jr:|js:z	|j�|j�Wnt	t
fy"�ty3|jdt
jdd�Ynw|jr:|jr|jrN|jrHt�d�|js@|jrP|j�dSdS)z1Serve requests, after invoking :func:`prepare()`.��targetzError in HTTPServer.serveTrg�������?N)�	threading�Threadr�rzr�r{r��run�expiration_intervalrrrrrr�_stopping_for_interruptrv�sleeprXrCrCrD�servejs,
���
��zHTTPServer.servecCs|��|��dS)zmRun the server forever.

        It is shortcut for invoking :func:`prepare()` then :func:`serve()`.
        N)r�r�rXrCrCrDrz�s	zHTTPServer.startccsF�|��tj|jd�}d|_|��z
|VW|��dS|��w)z4Context manager for running this server in a thread.r�TN)r�r�r�r��daemonrz�stop)r<�threadrCrCrD�_run_in_thread�s�zHTTPServer._run_in_threadcCs|jo|jjS)z>Flag whether it is allowed to add a new keep-alive connection.)r�r�r�rXrCrCrDr��sz'HTTPServer.can_add_keepalive_connectioncCs"|jr|j�|�dS|��dS)z7Put an idle connection back into the ConnectionManager.N)r�r��putrs�r<r�rCrCrD�put_conn�szHTTPServer.put_connr�cCsFtj�|�d��tj��|r!t��}tj�|�tj��dSdS)z�Write error message to log.

        :param msg: error message
        :type msg: str

        :param level: logging level
        :type level: int

        :param traceback: add traceback to output or not
        :type traceback: bool
        �
N)�sys�stderrr��flush�
traceback_�
format_exc)r<r�rr
ZtblinesrCrCrDr�s
�zHTTPServer.error_logc	CsB|�|j||||j|j|j�}|�||j�}|_|�|�|_|S)z.Create (or recreate) the actual socket object.)�prepare_socketrK�nodelayr�rN�bind_socketr��resolve_real_bind_addr)r<r$�typer�rrCrCrDr��s�	zHTTPServer.bindc
Cs�tr	td��d}zt�|j�WnEtyYn=ty4}zt|�}d|vr*�WYd}~n'd}~wtyV}zt|�}d|vrLd|vrLd|vrL�WYd}~nd}~ww|j|t	j
t	jd|j|j
|jd	�}z
	t�|��|�d
}Wnty�d}Ynwz|�||�}Wn
t	jy�|���w|�|�}z!	|s�zt�||�Wnty�tj||dd�Ynwd
}Wn	ty�Ynw|s�|jd
tjd�||_||_	|S)z*Create (or recreate) a UNIX socket object.z0AF_UNIX sockets are not supported under Windows.i�zJremove() argument 1 must be encoded string without null bytes, not unicodeNz'unlink: embedded null character in pathzembedded null bytez0argument must be a string without NUL charactersr)rKr$r�r�r�r�rNTF)�follow_symlinksz(Failed to set socket fs mode permissions)r)r#r/r��unlinkrKr��	TypeErrorr�r�r�r%r�r�r�rN�fchmod�filenor�r�rsr��lchmodr�chmodrrr)r<rKZfs_permissionsZtyp_err�err_msgZval_errrZFS_PERMS_SETrCrCrDr��s��������
�
��
����zHTTPServer.bind_unix_socketcCs�|dd�\}}|dk}|jtjtjhvrtd��|rtd��ttd�r/|�tjtjd�dSttd�r?|�tjtj	d�dSt
rL|�tjtjd�dStd��)	Nr�rzCannot reuse a non-IP socketz"Cannot reuse an ephemeral port (0)�SO_REUSEPORT_LBr�SO_REUSEPORTz,Current platform does not support port reuse)
r$r�r�rr/�hasattr�
setsockoptr)r�r�r#�SO_REUSEADDRr&)�socket_rKZ_hostr��IS_EPHEMERAL_PORTrCrCrD�_make_socket_reusable!s

�z HTTPServer._make_socket_reusablec
Cs�t�|||�}t�|�|dd�\}	}
|
dk}|r!|j||d�ts/|s/	|�tjtjd�|rAt|t	t
f�sA|�tjtjd�|durJ|�
|�}ttd�oW|tjkoW|	dv}|r{t�ttj��|�tjtjd�Wd�|S1svwY|S)z%Create and prepare the socket object.Nr�r�r�rKrr>z::0z::z	::0.0.0.0)r�rZprevent_socket_inheritancer�r#r�r)r�r�r�r��IPPROTO_TCP�TCP_NODELAYr�r�rr�r�rr�rr)
�clsrKr$r�r�r�r�rNrr�r�r�Zlistening_ipv6rCrCrDr�;s:



���
�	�	zHTTPServer.prepare_socketcCs|�|�|S)z#Bind the socket to given interface.)r�r�rCrCrDr�vs
zHTTPServer.bind_socketcCs>|��}|jtjtjhvr	|dd�St|t�rt|�}|S)z/Retrieve actual bind address from bound socket.Nr�)�getsocknamer$r�r�rr�r�rr�rCrCrDr�|s�
z!HTTPServer.resolve_real_bind_addrcCs6z	|j�|�WdStjy|j�|�YdSw)z#Process an incoming HTTPConnection.N)rLr�rP�FullrRr�rCrCrD�process_conn�s
�zHTTPServer.process_conncCrx)zFlag interrupt of the server.)r~rXrCrCrDr{�szHTTPServer.interruptcCs
|jtuS)z8Return whether the server is responding to an interrupt.)r~r�rXrCrCrDr��s
z"HTTPServer._stopping_for_interruptcCs@t|_t|t�r
|�d�t|t�r|�d�|��||_dS)aPerform the shutdown of this server and save the exception.

        Typically invoked by a worker thread in
        :py:mod:`~cheroot.workers.threadpool`, the exception is raised
        from the thread running :py:meth:`serve` once :py:meth:`stop`
        has completed.
        z!Keyboard Interrupt: shutting downz SystemExit raised: shutting downN)r�r~r�rrrr�)r<r{rCrCrDr{�s	




c
Csr|jsdSd|_|j�t�|jdur|jt��|j7_d|_|j��t	|dd�}|r�t
|jtt
f�s�z|��dd�\}}Wntjy_}z|jdtjvrU�WYd}~nDd}~wwt�||tjtj�D]4}|\}}}}	}
d}zt�|||�}|�d�|�||f�|��Wqjtjy�|r�|��Yqjwt|d�r�|��d|_|j��|j�|j�dS)z5Gracefully shutdown a server that is serving forever.NFr�r�rg�?rs)r�rRr�r�rsrtrvr�r�r�r�rKr�r�r�r�r�r�rr�r�r�r�r��connectrsr�rL�shutdown_timeout)r<rr�r�r�rfr�r�r�r�Z_sarVrCrCrDr��sT

����
��

zHTTPServer.stop)rIrbNFFF)rr�Fr})F);rJrKrLrMryr~r�rSrTr�r�r�r�r�r�rrMrr�r�r�r�rZConnectionClassr�rrrNZkeep_alive_conn_limitrVrOrYrwrHrK�setterr|r�r�r�rzr��contextmanagerr�r�r�rr�r��staticmethodr��classmethodr�r�r�r�r{r�r�rCrCrCrDr�s�

�,7

K



T
	�:




rc@s eZdZdZdd�Zdd�ZdS)rzDBase class to interface HTTPServer with other systems, such as WSGI.cCs
||_dS)zuInitialize Gateway instance with request.

        Args:
            req (HTTPRequest): current HTTP request
        N)r)r<rrCrCrDrV�s
zGateway.__init__cCst�)z>Process the current request. Must be overridden in a subclass.)r&rXrCrCrDr��rxzGateway.respondN)rJrKrLrMrVr�rCrCrCrDr�srz%cheroot.ssl.builtin.BuiltinSSLAdapterz&cheroot.ssl.pyopenssl.pyOpenSSLAdapter)�builtinZ	pyopensslr�cCs�t|��}t|t�rW|�d�}||dd�}|d|�}z
tj|}|dur*t�Wnty>t|t	�t
�dg�}Ynwzt||�}W|StyVtd||f��w|S)z/Return an SSL adapter class for the given name.�.rNrz!'%s' object has no attribute '%s')
�ssl_adaptersr�r�r��rfindr��modules�KeyError�
__import__�globals�localsr�r)�nameZadapterZlast_dotZ	attr_nameZmod_path�modrCrCrDr	s,


���
��r)r�)KrMr��email.utilsr�rFrr��platformrP�rer�r�r�rvr
r��urllib.parser��	functoolsrrrrrZ_compatrrr	r	r
�workersr�__all__�systemr#r�r�ZIS_GAEr5r9r6�ImportErrorr*r�rrrrdr0r3r2r6r�reZASTERISKr�r��compiler;r�rr�r9r+rr
rrrrrrrr�rrCrCrCrD�<module>s�C
�





GaZB`�