a
    õ£Be¡Œ  ã                	   @   s>  d 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dlZddlZddlmZ ddlZddlZddlmZmZmZmZ ddlmZmZmZ ddlmZ dd	lmZm Z  e ddl!Z!dd
l!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, e!j-�r ddl!m.Z. ddl/m0Z0 ddl1Z1e	dƒe2e2dœdd„ƒZ3G dd„ dej4j5ƒZ6G dd„ de7ƒZ8G dd„ de9ƒZ:G dd„ de9ƒZ;G dd„ de7ƒZ<G dd„ de7ƒZ=G dd„ de7ƒZ>e2e(de'e2e2f e$e"e2e2f  e"e"e2e2f df f e2d œd!d"„Z?G d#d$„ d$eƒZ@e2e)e"e)eA e)eA f  d%œd&d'„ZBe)eA e)eA eAe2d(œd)d*„ZCe2e)eA d+œd,d-„ZDd^e2eEe'e2e$eE f e'e2e$e@ f e)e6 dd.œd/d0„ZFeEeEe'e2e$eE f e'e2e$e@ f dd1œd2d3„ZGe(eAeHeIejJejf e2d4œd5d6„ZKe Ld7g d8¢¡ZMe Nd9¡ZOe2eMd:œd;d<„ZPe Ld=g d>¢¡ZQe Nd?¡ZRe2eQd:œd@dA„ZSe2e+e2ddf dBœdCdD„ZTe2e"e2e'e2e2f f d:œdEdF„ZUe2e'e2e2f e2dGœdHdI„ZVe(e2eEf e(e2eEf eEdJœdKdL„ZWdMdN„ ZXe NdO¡ZYe2e"e2e)eA f dPœdQdR„ZZe'e2e$e, f e#e"e2e,f  dSœdTdU„Z[e NdV¡Z\e NdW¡Z]dXj^Z_e2e2dBœdYdZ„Z`e2e'e2e2f d[œd\d]„ZadS )_z¤HTTP utility code shared by clients and servers.

This module also defines the `HTTPServerRequest` class which is exposed
via `tornado.web.RequestHandler.request`.
é    N)Ú	lru_cache)Ú	responses)ÚSSLError)Ú	urlencodeÚurlparseÚ
urlunparseÚ	parse_qsl)Ú
native_strÚparse_qs_bytesÚutf8)Úgen_log)Ú
ObjectDictÚunicode_type)ÚTupleÚIterableÚListÚMappingÚIteratorÚDictÚUnionÚOptionalÚ	AwaitableÚ	GeneratorÚAnyStr)ÚDeque)ÚFutureiè  ©ÚnameÚreturnc                 C   s   d  dd„ |  d¡D ƒ¡S )ziMap a header name to Http-Header-Case.

    >>> _normalize_header("coNtent-TYPE")
    'Content-Type'
    ú-c                 S   s   g | ]}|  ¡ ‘qS © )Ú
capitalize)Ú.0Úwr    r    úS/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/tornado/httputil.pyÚ
<listcomp>I   ó    z%_normalize_header.<locals>.<listcomp>)ÚjoinÚsplit)r   r    r    r$   Ú_normalize_headerB   s    r)   c                   @   st  e Zd ZdZejeeee f ddœdd„ƒZ	ejeeef ddœdd„ƒZ	eje
eef ddœdd„ƒZ	ejedd	œd
d„ƒZ	ejeddœdd„Z	eeddœdd„Zeee dœdd„Zee
eef  dœdd„Zeddœdd„Zeed dœdd„ƒZeeddœdd„Zeedœdd„Zeddœd d!„Zedœd"d#„Zeej dœd$d%„Zd dœd&d'„ZeZedœd(d)„ZeZdS )*ÚHTTPHeadersaÝ  A dictionary that maintains ``Http-Header-Case`` for all keys.

    Supports multiple values per key via a pair of new methods,
    `add()` and `get_list()`.  The regular dictionary interface
    returns a single value per key, with multiple values joined by a
    comma.

    >>> h = HTTPHeaders({"content-type": "text/html"})
    >>> list(h.keys())
    ['Content-Type']
    >>> h["Content-Type"]
    'text/html'

    >>> h.add("Set-Cookie", "A=B")
    >>> h.add("Set-Cookie", "C=D")
    >>> h["set-cookie"]
    'A=B,C=D'
    >>> h.get_list("set-cookie")
    ['A=B', 'C=D']

    >>> for (k,v) in sorted(h.get_all()):
    ...    print('%s: %s' % (k,v))
    ...
    Content-Type: text/html
    Set-Cookie: A=B
    Set-Cookie: C=D
    N)Ú_HTTPHeaders__argr   c                 C   s   d S ©Nr    ©Úselfr+   r    r    r$   Ú__init__i   s    zHTTPHeaders.__init__c                 C   s   d S r,   r    r-   r    r    r$   r/   m   s    )Úargsr   c                 G   s   d S r,   r    )r.   r0   r    r    r$   r/   q   s    )Úkwargsr   c                 K   s   d S r,   r    )r.   r1   r    r    r$   r/   u   s    )r0   r1   r   c                 O   sp   i | _ i | _d | _t|ƒdkr\t|ƒdkr\t|d tƒr\|d  ¡ D ]\}}|  ||¡ qDn| j|i |¤Ž d S )Né   r   )	Ú_dictÚ_as_listÚ	_last_keyÚlenÚ
isinstancer*   Úget_allÚaddÚupdate)r.   r0   r1   ÚkÚvr    r    r$   r/   y   s    &)r   Úvaluer   c                 C   sR   t |ƒ}|| _|| v rFt| | ƒd t|ƒ | j|< | j|  |¡ n|| |< dS )z#Adds a new value for the given key.ú,N)r)   r5   r	   r3   r4   Úappend©r.   r   r=   Ú	norm_namer    r    r$   r9   ‡   s    ÿzHTTPHeaders.addr   c                 C   s   t |ƒ}| j |g ¡S )z2Returns all values for the given header as a list.)r)   r4   Úget©r.   r   rA   r    r    r$   Úget_list“   s    zHTTPHeaders.get_list©r   c                 c   s,   | j  ¡ D ]\}}|D ]}||fV  qq
dS )zžReturns an iterable of all (name, value) pairs.

        If a header has multiple values, multiple pairs will be
        returned with the same name.
        N)r4   Úitems)r.   r   Úvaluesr=   r    r    r$   r8   ˜   s    zHTTPHeaders.get_all©Úliner   c                 C   sœ   |d   ¡ rX| jdu rtdƒ‚d| ¡  }| j| j d  |7  < | j| j  |7  < n@z| dd¡\}}W n ty†   tdƒ‚Y n0 |  || 	¡ ¡ dS )	zÃUpdates the dictionary with a single header line.

        >>> h = HTTPHeaders()
        >>> h.parse_line("Content-Type: text/html")
        >>> h.get('content-type')
        'text/html'
        r   Nz.first header line cannot start with whitespaceú éÿÿÿÿú:r2   zno colon in header line)
Úisspacer5   ÚHTTPInputErrorÚlstripr4   r3   r(   Ú
ValueErrorr9   Ústrip)r.   rI   Znew_partr   r=   r    r    r$   Ú
parse_line¢   s    
zHTTPHeaders.parse_line)Úheadersr   c                 C   s>   | ƒ }|  d¡D ](}| d¡r*|dd… }|r| |¡ q|S )a„  Returns a dictionary from HTTP header text.

        >>> h = HTTPHeaders.parse("Content-Type: text/html\r\nContent-Length: 42\r\n")
        >>> sorted(h.items())
        [('Content-Length', '42'), ('Content-Type', 'text/html')]

        .. versionchanged:: 5.1

           Raises `HTTPInputError` on malformed headers instead of a
           mix of `KeyError`, and `ValueError`.

        Ú
úNrK   )r(   ÚendswithrR   )ÚclsrS   ÚhrI   r    r    r$   Úparse¸   s    
zHTTPHeaders.parsec                 C   s"   t |ƒ}|| j|< |g| j|< d S r,   ©r)   r3   r4   r@   r    r    r$   Ú__setitem__Ò   s    
zHTTPHeaders.__setitem__c                 C   s   | j t|ƒ S r,   )r3   r)   )r.   r   r    r    r$   Ú__getitem__×   s    zHTTPHeaders.__getitem__c                 C   s   t |ƒ}| j|= | j|= d S r,   rZ   rC   r    r    r$   Ú__delitem__Ú   s    zHTTPHeaders.__delitem__c                 C   s
   t | jƒS r,   )r6   r3   ©r.   r    r    r$   Ú__len__ß   s    zHTTPHeaders.__len__c                 C   s
   t | jƒS r,   )Úiterr3   r^   r    r    r$   Ú__iter__â   s    zHTTPHeaders.__iter__c                 C   s   t | ƒS r,   )r*   r^   r    r    r$   Úcopyå   s    zHTTPHeaders.copyc                 C   s2   g }|   ¡ D ]\}}| d||f ¡ qd |¡S )Nz%s: %s
Ú )r8   r?   r'   )r.   Úlinesr   r=   r    r    r$   Ú__str__î   s    zHTTPHeaders.__str__)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚtypingÚoverloadr   Ústrr   r/   r   ÚAnyr9   rD   r   r8   rR   ÚclassmethodrY   r[   r\   r]   Úintr_   r   ra   rb   Ú__copy__re   Ú__unicode__r    r    r    r$   r*   L   s2   
r*   c                   @   sâ   e Zd ZdZdZdZdZdee ee eee	 ee
 ee eeeed f  ed ed ee ddœdd	„Zeeeejjf d
œdd„ƒZed
œdd„Zed
œdd„Zdeedee
f dœdd„Zdd
œdd„Zed
œdd„ZdS )ÚHTTPServerRequesta7
  A single HTTP request.

    All attributes are type `str` unless otherwise noted.

    .. attribute:: method

       HTTP request method, e.g. "GET" or "POST"

    .. attribute:: uri

       The requested uri.

    .. attribute:: path

       The path portion of `uri`

    .. attribute:: query

       The query portion of `uri`

    .. attribute:: version

       HTTP version specified in request, e.g. "HTTP/1.1"

    .. attribute:: headers

       `.HTTPHeaders` dictionary-like object for request headers.  Acts like
       a case-insensitive dictionary with additional methods for repeated
       headers.

    .. attribute:: body

       Request body, if present, as a byte string.

    .. attribute:: remote_ip

       Client's IP address as a string.  If ``HTTPServer.xheaders`` is set,
       will pass along the real IP address provided by a load balancer
       in the ``X-Real-Ip`` or ``X-Forwarded-For`` header.

    .. versionchanged:: 3.1
       The list format of ``X-Forwarded-For`` is now supported.

    .. attribute:: protocol

       The protocol used, either "http" or "https".  If ``HTTPServer.xheaders``
       is set, will pass along the protocol used by a load balancer if
       reported via an ``X-Scheme`` header.

    .. attribute:: host

       The requested hostname, usually taken from the ``Host`` header.

    .. attribute:: arguments

       GET/POST arguments are available in the arguments property, which
       maps arguments names to lists of values (to support multiple values
       for individual names). Names are of type `str`, while arguments
       are byte strings.  Note that this is different from
       `.RequestHandler.get_argument`, which returns argument values as
       unicode strings.

    .. attribute:: query_arguments

       Same format as ``arguments``, but contains only arguments extracted
       from the query string.

       .. versionadded:: 3.2

    .. attribute:: body_arguments

       Same format as ``arguments``, but contains only arguments extracted
       from the request body.

       .. versionadded:: 3.2

    .. attribute:: files

       File uploads are available in the files property, which maps file
       names to lists of `.HTTPFile`.

    .. attribute:: connection

       An HTTP request is attached to a single HTTP connection, which can
       be accessed through the "connection" attribute. Since connections
       are typically kept open in HTTP/1.1, multiple requests can be handled
       sequentially on a single connection.

    .. versionchanged:: 4.0
       Moved from ``tornado.httpserver.HTTPRequest``.
    NúHTTP/1.0ÚHTTPFileÚHTTPConnectionÚRequestStartLine)ÚmethodÚuriÚversionrS   ÚbodyÚhostÚfilesÚ
connectionÚ
start_lineÚserver_connectionr   c                 C   sö   |	d ur|	\}}}|| _ || _|| _|p,tƒ | _|p6d| _t|dd ƒ}t|dd ƒ| _t|ddƒ| _|pt| j 	d¡ptd| _
t| j
 ¡ ƒd | _|p’i | _|| _|
| _t ¡ | _d | _|d urÎ| d	¡\| _}| _t| jd
d�| _t | j¡| _i | _d S )Nr&   ÚcontextÚ	remote_ipÚprotocolÚhttpÚHostz	127.0.0.1r   ú?T©Úkeep_blank_values)rw   rx   ry   r*   rS   rz   Úgetattrr�   r‚   rB   r{   Úsplit_host_and_portÚlowerZ	host_namer|   r}   r   ÚtimeÚ_start_timeÚ_finish_timeÚ	partitionÚpathÚqueryr
   Ú	argumentsrb   ÚdeepcopyZquery_argumentsÚbody_arguments)r.   rw   rx   ry   rS   rz   r{   r|   r}   r~   r   r€   Úsepr    r    r$   r/   Z  s,    



zHTTPServerRequest.__init__rE   c              	   C   s€   t | dƒsztj ¡ | _d| jv rzzt| jd ƒ}W n tyD   Y n60 | ¡ D ]*\}}z|| j|< W qN tyv   Y qN0 qN| jS )z0A dictionary of ``http.cookies.Morsel`` objects.Ú_cookiesÚCookie)	Úhasattrrƒ   ÚcookiesÚSimpleCookier•   rS   Úparse_cookieÚ	ExceptionrF   )r.   Úparsedr;   r<   r    r    r$   r˜   ‚  s    
ÿ
zHTTPServerRequest.cookiesc                 C   s   | j d | j | j S )z+Reconstructs the full URL for this request.z://)r‚   r{   rx   r^   r    r    r$   Úfull_url™  s    zHTTPServerRequest.full_urlc                 C   s(   | j du rt ¡ | j S | j | j S dS )z?Returns the amount of time it took for this request to execute.N)r�   r‹   rŒ   r^   r    r    r$   Úrequest_time�  s    
zHTTPServerRequest.request_timeF)Úbinary_formr   c                 C   s>   z$| j du rW dS | j jjj|d�W S  ty8   Y dS 0 dS )a>  Returns the client's SSL certificate, if any.

        To use client certificates, the HTTPServer's
        `ssl.SSLContext.verify_mode` field must be set, e.g.::

            ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
            ssl_ctx.load_cert_chain("foo.crt", "foo.key")
            ssl_ctx.load_verify_locations("cacerts.pem")
            ssl_ctx.verify_mode = ssl.CERT_REQUIRED
            server = HTTPServer(app, ssl_options=ssl_ctx)

        By default, the return value is a dictionary (or None, if no
        client certificate is present).  If ``binary_form`` is true, a
        DER-encoded form of the certificate is returned instead.  See
        SSLSocket.getpeercert() in the standard library for more
        details.
        http://docs.python.org/library/ssl.html#sslsocket-objects
        N)rŸ   )r}   ÚstreamÚsocketÚgetpeercertr   )r.   rŸ   r    r    r$   Úget_ssl_certificate¤  s    

ÿz%HTTPServerRequest.get_ssl_certificatec                 C   sN   t | j dd¡| j| j| j| jƒ | j ¡ D ]\}}| j |g ¡ 	|¡ q,d S )NúContent-Typerc   )
Úparse_body_argumentsrS   rB   rz   r“   r|   rF   r‘   Ú
setdefaultÚextend)r.   r;   r<   r    r    r$   Ú_parse_bodyÃ  s    ûzHTTPServerRequest._parse_bodyc                    s,   d}d  ‡ fdd„|D ƒ¡}dˆ jj|f S )N)r‚   r{   rw   rx   ry   r�   z, c                    s   g | ]}d |t ˆ |ƒf ‘qS )z%s=%r)rˆ   )r"   Únr^   r    r$   r%   Ñ  r&   z.HTTPServerRequest.__repr__.<locals>.<listcomp>z%s(%s))r'   Ú	__class__rf   )r.   Úattrsr0   r    r^   r$   Ú__repr__Ï  s    zHTTPServerRequest.__repr__)
NNrs   NNNNNNN)F)rf   rg   rh   ri   r�   r�   Z_body_futurer   rl   r*   Úbytesr   r   Úobjectr/   Úpropertyrƒ   r˜   ÚMorselr�   Úfloatrž   Úboolr   r£   r¨   r¬   r    r    r    r$   rr   ÷   sL   \          õô( ÿþrr   c                   @   s   e Zd ZdZdS )rN   zqException class for malformed HTTP requests or responses
    from remote sources.

    .. versionadded:: 4.0
    N©rf   rg   rh   ri   r    r    r    r$   rN   Õ  s   rN   c                   @   s   e Zd ZdZdS )ÚHTTPOutputErrorzJException class for errors in HTTP output.

    .. versionadded:: 4.0
    Nr³   r    r    r    r$   r´   ß  s   r´   c                   @   s2   e Zd ZdZedddœdd„Zeddœd	d
„ZdS )ÚHTTPServerConnectionDelegatez_Implement this interface to handle requests from `.HTTPServer`.

    .. versionadded:: 4.0
    ru   ÚHTTPMessageDelegate)Úserver_connÚrequest_connr   c                 C   s
   t ƒ ‚dS )aj  This method is called by the server when a new request has started.

        :arg server_conn: is an opaque object representing the long-lived
            (e.g. tcp-level) connection.
        :arg request_conn: is a `.HTTPConnection` object for a single
            request/response exchange.

        This method should return a `.HTTPMessageDelegate`.
        N©ÚNotImplementedError)r.   r·   r¸   r    r    r$   Ústart_requestî  s    z*HTTPServerConnectionDelegate.start_requestN)r·   r   c                 C   s   dS )zµThis method is called when a connection has been closed.

        :arg server_conn: is a server connection that has previously been
            passed to ``start_request``.
        Nr    )r.   r·   r    r    r$   Úon_closeü  s    z%HTTPServerConnectionDelegate.on_close)rf   rg   rh   ri   r®   r»   r¼   r    r    r    r$   rµ   è  s
   þrµ   c                   @   sb   e Zd ZdZed eeed  dœdd„Ze	eed  dœdd	„Z
dd
œdd„Zdd
œdd„ZdS )r¶   z_Implement this interface to handle an HTTP request or response.

    .. versionadded:: 4.0
    ©rv   ÚResponseStartLineN)r~   rS   r   c                 C   s   dS )aÂ  Called when the HTTP headers have been received and parsed.

        :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`
            depending on whether this is a client or server message.
        :arg headers: a `.HTTPHeaders` instance.

        Some `.HTTPConnection` methods can only be called during
        ``headers_received``.

        May return a `.Future`; if it does the body will not be read
        until it is done.
        Nr    )r.   r~   rS   r    r    r$   Úheaders_received  s    z$HTTPMessageDelegate.headers_received©Úchunkr   c                 C   s   dS )ziCalled when a chunk of data has been received.

        May return a `.Future` for flow control.
        Nr    ©r.   rÁ   r    r    r$   Údata_received  s    z!HTTPMessageDelegate.data_receivedrE   c                 C   s   dS )z6Called after the last chunk of data has been received.Nr    r^   r    r    r$   Úfinish&  s    zHTTPMessageDelegate.finishc                 C   s   dS )zÉCalled if the connection is closed without finishing the request.

        If ``headers_received`` is called, either ``finish`` or
        ``on_connection_close`` will be called, but not both.
        Nr    r^   r    r    r$   Úon_connection_close*  s    z'HTTPMessageDelegate.on_connection_close)rf   rg   rh   ri   r   r*   r   r   r¿   r­   rÃ   rÄ   rÅ   r    r    r    r$   r¶     s   
ür¶   c                   @   sL   e Zd ZdZded eee ddœdd„Zeddœd	d
„Z	ddœdd„Z
dS )ru   zYApplications use this interface to write their responses.

    .. versionadded:: 4.0
    Nr½   zFuture[None])r~   rS   rÁ   r   c                 C   s
   t ƒ ‚dS )a  Write an HTTP header block.

        :arg start_line: a `.RequestStartLine` or `.ResponseStartLine`.
        :arg headers: a `.HTTPHeaders` instance.
        :arg chunk: the first (optional) chunk of data.  This is an optimization
            so that small responses can be written in the same call as their
            headers.

        The ``version`` field of ``start_line`` is ignored.

        Returns a future for flow control.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed.
        Nr¹   )r.   r~   rS   rÁ   r    r    r$   Úwrite_headers9  s    zHTTPConnection.write_headersrÀ   c                 C   s
   t ƒ ‚dS )z¥Writes a chunk of body data.

        Returns a future for flow control.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed.
        Nr¹   rÂ   r    r    r$   ÚwriteQ  s    	zHTTPConnection.writerE   c                 C   s
   t ƒ ‚dS )z3Indicates that the last body data has been written.Nr¹   r^   r    r    r$   rÄ   \  s    zHTTPConnection.finish)N)rf   rg   rh   ri   r   r*   r   r­   rÆ   rÇ   rÄ   r    r    r    r$   ru   3  s   	 üûru   .)Úurlr0   r   c                 C   s´   |du r| S t | ƒ}t|tƒr<t|jdd�}| | ¡ ¡ nDt|tƒsPt|tƒrjt|jdd�}| |¡ nd 	t
|ƒ¡}t|ƒ‚t|ƒ}t|d |d |d |d ||d	 fƒ} | S )
a  Concatenate url and arguments regardless of whether
    url has existing query parameters.

    ``args`` may be either a dictionary or a list of key-value pairs
    (the latter allows for multiple values with the same key.

    >>> url_concat("http://example.com/foo", dict(c="d"))
    'http://example.com/foo?c=d'
    >>> url_concat("http://example.com/foo?a=b", dict(c="d"))
    'http://example.com/foo?a=b&c=d'
    >>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
    'http://example.com/foo?a=b&c=d&c=d2'
    NTr†   z7'args' parameter should be dict, list or tuple. Not {0}r   r2   é   é   é   )r   r7   Údictr   r�   r§   rF   ÚlistÚtupleÚformatÚtypeÚ	TypeErrorr   r   )rÈ   r0   Ú
parsed_urlZparsed_queryÚerrZfinal_queryr    r    r$   Ú
url_concata  s0    
ÿúÿ
rÔ   c                   @   s*   e Zd ZU dZeed< eed< eed< dS )rt   zËRepresents a file uploaded via a form.

    For backwards compatibility, its instance attributes are also
    accessible as dictionary keys.

    * ``filename``
    * ``body``
    * ``content_type``
    Úfilenamerz   Úcontent_typeN)rf   rg   rh   ri   rl   Ú__annotations__r­   r    r    r    r$   rt   �  s   

rt   )Úrange_headerr   c                 C   sœ   |   d¡\}}}| ¡ | ¡  }}|dkr.dS |  d¡\}}}zt|ƒ}t|ƒ}W n tyf   Y dS 0 |dur”|du rŒ|dkr”| }d}n|d7 }||fS )ag  Parses a Range header.

    Returns either ``None`` or tuple ``(start, end)``.
    Note that while the HTTP headers use inclusive byte positions,
    this method returns indexes suitable for use in slices.

    >>> start, end = _parse_request_range("bytes=1-2")
    >>> start, end
    (1, 3)
    >>> [0, 1, 2, 3, 4][start:end]
    [1, 2]
    >>> _parse_request_range("bytes=6-")
    (6, None)
    >>> _parse_request_range("bytes=-6")
    (-6, None)
    >>> _parse_request_range("bytes=-0")
    (None, 0)
    >>> _parse_request_range("bytes=")
    (None, None)
    >>> _parse_request_range("foo=42")
    >>> _parse_request_range("bytes=1-2,6-10")

    Note: only supports one range (ex, ``bytes=1-2,6-10`` is not allowed).

    See [0] for the details of the range header.

    [0]: http://greenbytes.de/tech/webdav/draft-ietf-httpbis-p5-range-latest.html#byte.ranges
    ú=r­   Nr   r   r2   )rŽ   rQ   Ú_int_or_nonerP   )rØ   ÚunitÚ_r=   Zstart_bZend_bÚstartÚendr    r    r$   Ú_parse_request_range   s"    rß   )rÝ   rÞ   Útotalr   c                 C   s"   | pd} |p|d }d| ||f S )zèReturns a suitable Content-Range header:

    >>> print(_get_content_range(None, 1, 4))
    bytes 0-0/4
    >>> print(_get_content_range(1, 3, 4))
    bytes 1-2/4
    >>> print(_get_content_range(None, None, 4))
    bytes 0-3/4
    r   r2   zbytes %s-%s/%sr    )rÝ   rÞ   rà   r    r    r$   Ú_get_content_rangeÓ  s    
rá   )Úvalr   c                 C   s   |   ¡ } | dkrd S t| ƒS )Nrc   )rQ   ro   )râ   r    r    r$   rÚ   â  s    rÚ   )rÖ   rz   r‘   r|   rS   r   c              
   C   sV  |   d¡rš|r*d|v r*t d|d ¡ dS zt|dd�}W n4 tyn } zt d|¡ i }W Y d}~n
d}~0 0 | ¡ D ]\}}|rx| |g ¡ |¡ qxn¸|   d¡�rR|rÆd|v rÆt d|d ¡ dS zX|  d	¡}	|	D ]<}
|
 	¡  
d
¡\}}}|dkrÖ|rÖtt|ƒ|||ƒ  �qqÖtdƒ‚W n2 t�yP } zt d|¡ W Y d}~n
d}~0 0 dS )aF  Parses a form request body.

    Supports ``application/x-www-form-urlencoded`` and
    ``multipart/form-data``.  The ``content_type`` parameter should be
    a string and ``body`` should be a byte string.  The ``arguments``
    and ``files`` parameters are dictionaries that will be updated
    with the parsed contents.
    z!application/x-www-form-urlencodedzContent-Encodingz Unsupported Content-Encoding: %sNTr†   z&Invalid x-www-form-urlencoded body: %szmultipart/form-dataú;rÙ   Úboundaryzmultipart boundary not foundzInvalid multipart/form-data: %s)Ú
startswithr   Úwarningr
   r›   rF   r¦   r§   r(   rQ   rŽ   Úparse_multipart_form_datar   rP   )rÖ   rz   r‘   r|   rS   Zuri_argumentsÚer   rG   ÚfieldsÚfieldr;   r”   r<   r    r    r$   r¥   é  s<    
ÿÿ
r¥   )rä   Údatar‘   r|   r   c                 C   s^  |   d¡r |  d¡r | dd… } | d|  d ¡}|dkrHt d¡ dS |d|…  d|  d ¡}|D ]ò}|spqf| d¡}|dkrŽt d	¡ qft |d|…  	d
¡¡}| 
dd¡}	t|	ƒ\}
}|
dksÐ| d¡sÜt d¡ qf||d d… }| 
d¡�st d¡ qf|d }| 
d¡�rF| 
dd¡}| |g ¡ t|d ||d�¡ qf| |g ¡ |¡ qfdS )a]  Parses a ``multipart/form-data`` body.

    The ``boundary`` and ``data`` parameters are both byte strings.
    The dictionaries given in the arguments and files parameters
    will be updated with the contents of the body.

    .. versionchanged:: 5.1

       Now recognizes non-ASCII filenames in RFC 2231/5987
       (``filename*=``) format.
    ó   "r2   rK   s   --z.Invalid multipart/form-data: no final boundaryNs   
s   

z#multipart/form-data missing headerszutf-8zContent-Dispositionrc   z	form-datazInvalid multipart/form-dataé   éþÿÿÿr   z&multipart/form-data value missing namerÕ   r¤   zapplication/unknown)rÕ   rz   rÖ   )rå   rV   Úrfindr   ræ   r(   Úfindr*   rY   ÚdecoderB   Ú_parse_headerr¦   r?   rt   )rä   rë   r‘   r|   Zfinal_boundary_indexÚpartsÚpartZeohrS   Zdisp_headerZdispositionZdisp_paramsr=   r   Úctyper    r    r$   rç     sB    





ÿÿrç   )Útsr   c                 C   sh   t | ttfƒr| }nDt | ttjfƒr0t | ¡}n(t | tjƒrLt |  	¡ ¡}nt
d|  ƒ‚tjj|dd�S )a  Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    zunknown timestamp type: %rT)Úusegmt)r7   ro   r±   rÎ   r‹   Ústruct_timeÚcalendarÚtimegmÚdatetimeÚutctimetuplerÑ   ÚemailÚutilsÚ
formatdate)rö   Ztime_numr    r    r$   Úformat_timestampT  s    r   rv   )rw   r�   ry   z^HTTP/1\.[0-9]$rH   c                 C   sR   z|   d¡\}}}W n ty.   tdƒ‚Y n0 t |¡sFtd| ƒ‚t|||ƒS )zöReturns a (method, path, version) tuple for an HTTP 1.x request line.

    The response is a `collections.namedtuple`.

    >>> parse_request_start_line("GET /foo HTTP/1.1")
    RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
    rJ   zMalformed HTTP request linez/Malformed HTTP version in HTTP Request-Line: %r)r(   rP   rN   Ú_http_version_reÚmatchrv   )rI   rw   r�   ry   r    r    r$   Úparse_request_start_lines  s    
ÿr  r¾   )ry   ÚcodeÚreasonz (HTTP/1.[0-9]) ([0-9]+) ([^\r]*)c                 C   s@   t | ƒ} t | ¡}|stdƒ‚t| d¡t| d¡ƒ| d¡ƒS )zóReturns a (version, code, reason) tuple for an HTTP 1.x response line.

    The response is a `collections.namedtuple`.

    >>> parse_response_start_line("HTTP/1.1 200 OK")
    ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
    z!Error parsing response start liner2   rÉ   rÊ   )r	   Ú_http_response_line_rer  rN   r¾   Úgroupro   )rI   r  r    r    r$   Úparse_response_start_line�  s
    
r  )Úsr   c                 c   s˜   | d d… dkr”| dd … } |   d¡}|dkr`|  dd|¡|  dd|¡ d r`|   d|d ¡}q&|dk rpt| ƒ}| d |… }| ¡ V  | |d … } q d S )Nr2   rã   r   ú"z\"rÉ   )rð   Úcountr6   rQ   )r	  rÞ   Úfr    r    r$   Ú_parseparam§  s    
(
r  c                 C   sä   t d|  ƒ}t|ƒ}dg}|D ]P}| d¡}|dkr|d|…  ¡  ¡ }||d d…  ¡ }| |t|ƒf¡ qtj 	|¡}| 
d¡ i }	|D ]L\}}
tj |
¡}t|ƒdkrÒ|d dkrÒ|d	 dkrÒ|dd	… }||	|< qŽ||	fS )
aY  Parse a Content-type like header.

    Return the main content-type and a dictionary of options.

    >>> d = "form-data; foo=\"b\\\\a\\\"r\"; file*=utf-8''T%C3%A4st"
    >>> ct, d = _parse_header(d)
    >>> ct
    'form-data'
    >>> d['file'] == r'T\u00e4st'.encode('ascii').decode('unicode_escape')
    True
    >>> d['foo']
    'b\\a"r'
    rã   )ZDummyr=   rÙ   r   Nr2   rÉ   r
  rK   )r  Únextrð   rQ   rŠ   r?   r	   rý   rþ   Údecode_paramsÚpopÚcollapse_rfc2231_valuer6   )rI   ró   ÚkeyÚparamsÚpÚir   r=   Zdecoded_paramsÚpdictZdecoded_valuer    r    r$   rò   ´  s$    

$
rò   )r  r  r   c                 C   sT   |s| S | g}t | ¡ ƒD ].\}}|du r6| |¡ q| d||f ¡ qd |¡S )zìInverse of _parse_header.

    >>> _encode_header('permessage-deflate',
    ...     {'client_max_window_bits': 15, 'client_no_context_takeover': None})
    'permessage-deflate; client_max_window_bits=15; client_no_context_takeover'
    Nz%s=%sz; )ÚsortedrF   r?   r'   )r  r  Úoutr;   r<   r    r    r$   Ú_encode_header×  s    r  )ÚusernameÚpasswordr   c                 C   s@   t | tƒrt d| ¡} t |tƒr,t d|¡}t| ƒd t|ƒ S )z«Encodes a username/password pair in the format used by HTTP auth.

    The return value is a byte string in the form ``username:password``.

    .. versionadded:: 5.1
    ÚNFCó   :)r7   r   ÚunicodedataÚ	normalizer   )r  r  r    r    r$   Úencode_username_passwordë  s
    	

r   c                  C   s   dd l } |  ¡ S )Nr   )ÚdoctestZDocTestSuite)r!  r    r    r$   Údoctestsû  s    r"  z^(.+):(\d+)$)Únetlocr   c                 C   s8   t  | ¡}|r(| d¡}t| d¡ƒ}n| }d}||fS )z‡Returns ``(host, port)`` tuple from ``netloc``.

    Returned ``port`` will be ``None`` if not present.

    .. versionadded:: 4.1
    r2   rÉ   N)Ú
_netloc_rer  r  ro   )r#  r  r{   Úportr    r    r$   r‰     s    

r‰   )Úqsr   c                 c   s*   |   ¡ D ]\}}|D ]}||fV  qqdS )zgGenerator converting a result of ``parse_qs`` back to name-value pairs.

    .. versionadded:: 5.0
    N)rF   )r&  r;   Úvsr<   r    r    r$   Ú	qs_to_qsl  s    r(  z\\[0-3][0-7][0-7]z[\\].rc   c                 C   sN  | du st | ƒdk r| S | d dks0| d dkr4| S | dd… } d}t | ƒ}g }d|  krf|k �rFn nÜt | |¡}t | |¡}|s |s | | |d… ¡ �qFd }}|r¶| d¡}|rÄ| d¡}|�r|rØ||k �r| | ||… ¡ | | |d  ¡ |d }qP| | ||… ¡ | tt| |d |d … dƒƒ¡ |d }qPt|ƒS )	zÖHandle double quotes and escaping in cookie values.

    This method is copied verbatim from the Python 3.5 standard
    library (http.cookies._unquote) so we don't have to depend on
    non-public interfaces.
    NrÉ   r   r
  rK   r2   rí   é   )	r6   Ú
_OctalPattÚsearchÚ
_QuotePattr?   rÝ   Úchrro   Ú	_nulljoin)r	  r  r©   ÚresÚo_matchÚq_matchÚjr;   r    r    r$   Ú_unquote_cookie%  s6    	


$
r3  )Úcookier   c                 C   sr   i }|   tdƒ¡D ]Z}tdƒ|v r8|  tdƒd¡\}}ntdƒ| }}| ¡ | ¡  }}|s`|rt|ƒ||< q|S )a[  Parse a ``Cookie`` HTTP header into a dict of name/value pairs.

    This function attempts to mimic browser cookie parsing behavior;
    it specifically does not follow any of the cookie-related RFCs
    (because browsers don't either).

    The algorithm used is identical to that used by Django version 1.9.10.

    .. versionadded:: 4.4.2
    rã   rÙ   r2   rc   )r(   rl   rQ   r3  )r4  Z
cookiedictrÁ   r  râ   r    r    r$   rš   W  s    rš   )N)bri   rù   Úcollections.abcÚcollectionsrb   rû   Úemail.utilsrý   Ú	functoolsr   Úhttp.clientr   Úhttp.cookiesrƒ   ÚreÚsslr   r‹   r  Úurllib.parser   r   r   r   Ztornado.escaper	   r
   r   Ztornado.logr   Ztornado.utilr   r   rj   r   r   r   r   r   r   r   r   r   r   r   ÚTYPE_CHECKINGr   Úasyncior   Zunittestrl   r)   ÚabcÚMutableMappingr*   r®   rr   r›   rN   r´   rµ   r¶   ru   rÔ   rt   ro   rß   rá   rÚ   r­   r¥   rç   r±   rÎ   rø   r   Ú
namedtuplerv   Úcompiler  r  r¾   r  r  r  rò   r  r   r"  r$  r‰   r(  r*  r,  r'   r.  r3  rš   r    r    r    r$   Ú<module>   s²   4	 , _
	./.ÿû/þ3 ûú2û;þÿ
ÿ
 #þ
(


2