
    Mh                        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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.m/Z/ ddl0Z0ej1        j2        e3e3f         Z4nej1        j2        Z4dZ5 ej6        d          Z7 G d d          Z8 e	d          de3de3fd            Z9 G d de4          Z: G d d          Z; G d de<          Z= G d de<          Z> G d d          Z? G d d          Z@ G d  d!          ZAd"e3d#e'de&e3e3f         e#e!e3e3f                  e!e!e3e3f         d$f         f         de3fd%ZB G d& d'e          ZCd(e3de(e!e(eD         e(eD         f                  fd)ZEd*e(eD         d+e(eD         d,eDde3fd-ZFd.e3de(eD         fd/ZG	 dWd0e3d1eHd2e&e3e#eH         f         d3e&e3e#eC         f         d4e(e:         ddfd5ZId6eHd7eHd2e&e3e#eH         f         d3e&e3e#eC         f         ddf
d8ZJd9e'eDeKeLejM        ej        f         de3fd:ZN G d; d<e jO                  ZPd=e3dePfd>ZQ G d? d@e jO                  ZRd=e3deRfdAZSdBe3de*e3ddf         fdCZTd=e3de!e3e&e3e3f         f         fdDZUdEe3dFe&e3e3f         de3fdGZVdHe'e3eHf         dIe'e3eHf         deHfdJZWdK ZX ej6        dL          ZYdMe3de!e3e(eD         f         fdNZZdOe&e3e#e+         f         de"e!e3e+f                  fdPZ[ ej6        dQ          j\        Z]dRej^        de3fdSZ_dBe3de3fdTZ`dUe3de&e3e3f         fdVZadS )XzHTTP 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
to_unicode)
ObjectDictunicode_type)TupleIterableListMappingIteratorDictUnionOptional	Awaitable	GeneratorAnyStr)Deque)Futurez 	z [\x00-\x08\x0B\x0C\x0E-\x1F\x7F]c            
          e Zd ZdZ ej        d          Z ej        d          Z ej        d          Z ej        dej	         dej	         dej	         d          Z
 ej        d          Z ej        d	          Z ej        d
          Z ej        dej	         dej	         d          Z ej        dej	         dej	         dej	         dej	                   Z ej        d          Z ej        ej	         d          ZeZeZ ej        de
j	         dej	         d          Z ej        d          Z ej        dej	         dej	         d          Z ej        ej	         d          Z ej        dej	         dej	         dej	         d          Z ej        d          Z ej        dej	         dej	         dej	         d          ZdS )_ABNFa}  Class that holds a subset of ABNF rules from RFC 9110 and friends.

    Class attributes are re.Pattern objects, with the same name as in the RFC
    (with hyphens changed to underscores). Currently contains only the subset
    we use (which is why this class is not public). Unfortunately the fields
    cannot be alphabetized as they are in the RFCs because of dependencies.
    z[A-Za-z0-9\-._~]z[!$&'()*+,;=]z%[0-9A-Fa-f]{2}z(?:[\[\]:]||z)*z[0-9]*z[\x21-\x7E]z[\x80-\xFF]z(?:)z| |\t)*z[!#$%&'*+\-.^_`|~0-9A-Za-z]+z)(?::z)?zHTTP/[0-9]\.[0-9]z	(?:[\t ]|z)+(z) (z[0-9]{3}N)__name__
__module____qualname____doc__recompileuri_unreserveduri_sub_delimsuri_pct_encodedpatternuri_hosturi_portVCHARobs_textfield_vcharfield_valuetchartoken
field_namemethodhostHTTP_versionreason_phraserequest_targetrequest_linestatus_codestatus_line     P/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/tornado/httputil.pyr   r   N   s          RZ 344NRZ 011N bj!344Orzd~-dd0FddI`ddd H rz)$$H BJ~&&E rz.))H"*GEMGGH4DGGGHHK"*	V	V 	V	V 	V$/$7	V 	V@K@S	V 	V K
 BJ566EBJ5=+++,,EJF2:HX-HHH4DHHHIID 2:233LBJPEMPPH<LPPPQQM  RZK$7 : : :;;N2:RV^RR 6RR<;ORRR L "*[))K"*W\!WWk&9WWm>SWWW KKKr?   r   i  namereturnc                 f    d                     d |                     d          D                       S )ziMap a header name to Http-Header-Case.

    >>> _normalize_header("coNtent-TYPE")
    'Content-Type'
    -c                 6    g | ]}|                                 S r>   )
capitalize).0ws     r@   
<listcomp>z%_normalize_header.<locals>.<listcomp>   s     ===Q\\^^===r?   )joinsplit)rA   s    r@   _normalize_headerrL      s/     88==TZZ__===>>>r?   c            	       8   e Zd ZdZej        deeee         f         ddfd            Z	ej        deeef         ddfd            Z	ej        de
eef         ddfd            Z	ej        d	eddfd
            Z	dej        d	eddfdZ	dddedededdfdZdedee         fdZdee
eef                  fdZdddededdfdZedddededd fd            ZdededdfdZdedefdZdeddfdZdefdZdeej                 fdZddZeZdef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
    _HTTPHeaders__argrB   Nc                     d S Nr>   selfrO   s     r@   __init__zHTTPHeaders.__init__       r?   c                     d S rQ   r>   rR   s     r@   rT   zHTTPHeaders.__init__   rU   r?   argsc                     d S rQ   r>   )rS   rW   s     r@   rT   zHTTPHeaders.__init__   rU   r?   kwargsc                     d S rQ   r>   )rS   rY   s     r@   rT   zHTTPHeaders.__init__   rU   r?   c                 <   i | _         i | _        d | _        t          |          dk    rft          |          dk    rSt	          |d         t
                    r8|d                                         D ]\  }}|                     ||           d S  | j        |i | d S )N   r   )	_dict_as_list	_last_keylen
isinstancerN   get_alladdupdate)rS   rW   rY   kvs        r@   rT   zHTTPHeaders.__init__   s    
t99>>c&kkQ..:d1g{3S3S.Q))  1A  DK((((((r?   T_chars_are_bytesrA   valuerh   c                $   t           j                            |          st          d|z            |r?t           j                            t          |                    st          d|z            n,t                              |          rt          d|z            t          |          }|| _	        || v rRt          | |                   dz   t          |          z   | j        |<   | j        |                             |           dS || |<   dS )z#Adds a new value for the given key.zInvalid header name %rInvalid header value %r,N)r   r5   	fullmatchHTTPInputErrorr2   r   _FORBIDDEN_HEADER_CHARS_REsearchrL   r_   r
   r]   r^   append)rS   rA   ri   rh   	norm_names        r@   rc   zHTTPHeaders.add   s    ))$// 	B !9D!@AAA 	H$..z%/@/@AA H %%>%FGGGH
 *0077 H$%>%FGGG%d++	"4	?++c1Ju4E4EE Jy! M)$++E22222#DOOOr?   c                 V    t          |          }| j                            |g           S )z2Returns all values for the given header as a list.)rL   r^   getrS   rA   rr   s      r@   get_listzHTTPHeaders.get_list   s'    %d++	}  B///r?   c              #   ^   K   | j                                         D ]\  }}|D ]}||fV  	dS )zReturns an iterable of all (name, value) pairs.

        If a header has multiple values, multiple pairs will be
        returned with the same name.
        N)r^   items)rS   rA   valuesri   s       r@   rb   zHTTPHeaders.get_all   sZ       !M//11 	$ 	$LD& $ $Um####$	$ 	$r?   linec                   t          j        d|          x}r|d|                                         }|sdS |d         t          v r| j        t          d          d|                    t                    z   }|r:t          j        	                    |dd                   st          d|z            n,t                              |          rt          d|z            | j        | j                 d	xx         |z  cc<   | j        | j        xx         |z  cc<   dS 	 |                    d
d          \  }}n# t          $ r t          d          w xY w|                     ||                    t                    |           dS )a  Updates the dictionary with a single header line.

        >>> h = HTTPHeaders()
        >>> h.parse_line("Content-Type: text/html")
        >>> h.get('content-type')
        'text/html'
        >>> h.parse_line("Content-Length: 42\r\n")
        >>> h.get('content-type')
        'text/html'

        .. versionchanged:: 6.5
            Now supports lines with or without the trailing CRLF, making it possible
            to pass lines from AsyncHTTPClient's header_callback directly to this method.

        .. deprecated:: 6.5
           In Tornado 7.0, certain deprecated features of HTTP will become errors.
           Specifically, line folding and the use of LF (with CR) as a line separator
           will be removed.
        z\r?\n$Nr   z.first header line cannot start with whitespace r\   zInvalid header continuation %rrk   :zno colon in header linerg   )r'   rp   startHTTP_WHITESPACEr_   rn   stripr   r2   rm   ro   r^   r]   rK   
ValueErrorrc   )rS   rz   rh   mnew_partrA   ri   s          r@   
parse_linezHTTPHeaders.parse_line   s   ( 	)T***1 	% !''))$D 	F7o%% ~%$%UVVVTZZ888H O(228ABB<@@ V()IH)TUUUV .44X>> O()BX)MNNNM$.)"---9---Jt~&&&(2&&&&&@"jja00ee @ @ @$%>???@HHekk/22EU      s   D9 9Eheadersc                     |             }d}	 |                     d|          }|dk    r |                    ||d         |           n*|||dz            }|dz   }|                    ||           f|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`.

        r   T
r}   Nrg   r\   )findr   )clsr   rh   hr   lfrz   s          r@   parsezHTTPHeaders.parse#  s    8 CEE	BdE**BRxxWUVV_?OPPP526>*DFELL0@LAAA	B r?   c                 N    t          |          }|| j        |<   |g| j        |<   d S rQ   rL   r]   r^   )rS   rA   ri   rr   s       r@   __setitem__zHTTPHeaders.__setitem__N  s/    %d++	 %
9$)7i   r?   c                 6    | j         t          |                   S rQ   )r]   rL   )rS   rA   s     r@   __getitem__zHTTPHeaders.__getitem__S  s    z+D1122r?   c                 D    t          |          }| j        |= | j        |= d S rQ   r   ru   s      r@   __delitem__zHTTPHeaders.__delitem__V  s)    %d++	Jy!M)$$$r?   c                 *    t          | j                  S rQ   )r`   r]   rS   s    r@   __len__zHTTPHeaders.__len__[  s    4:r?   c                 *    t          | j                  S rQ   )iterr]   r   s    r@   __iter__zHTTPHeaders.__iter__^  s    DJr?   c                      t          |           S rQ   )rN   r   s    r@   copyzHTTPHeaders.copya  s    4   r?   c                     g }|                                  D ] \  }}|                    | d| d           !d                    |          S )Nz: r    )rb   rq   rJ   )rS   linesrA   ri   s       r@   __str__zHTTPHeaders.__str__j  sX    <<>> 	/ 	/KD%LLD--E---....wwu~~r?   )rB   rN   )r#   r$   r%   r&   typingoverloadr   strr   rT   r   Anyboolrc   rv   r   rb   r   classmethodr   r   r   r   intr   r   r   r   __copy__r   __unicode__r>   r?   r@   rN   rN      s        8 _gc49n5 $    _ _gc3h/ D    _ _eCHo $    _ _     _
)fj 
)C 
)D 
) 
) 
) 
) FJ $ $ $ $C $d $d $ $ $ $,0S 0T#Y 0 0 0 0
$%S/2 $ $ $ $ AE 1 1 1s 1 1 1 1 1 1f =A & & &C &d &m & & & [&T+ +C +D + + + +
3 3 3 3 3 3% % % % % %
     (6:.        ! ! ! ! H     KKKr?   rN   c                   p   e Zd ZdZdZdZdZ	 	 	 	 	 	 	 	 	 ddee         dee         dedee	         dee
         d	eeeed
         f                  ded         ded         dee         ddfdZedeeej        j        f         fd            ZdefdZdefdZ	 ddededee
f         fdZddZdef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.0r6   uriversionr   bodyfilesHTTPFile
connectionHTTPConnection
start_lineRequestStartLineserver_connectionrB   c
                    ||\  }}}|| _         || _        || _        |pt                      | _        |pd| _        t          |dd           }
t          |
dd           | _        t          |
dd          | _        	 | j        d         | _	        n-# t          $ r  |dk    rd| _	        nt          d	          Y nw xY wt          j	                            | j	                  s5t          t          j	        j                   t          d
| j	        z            d| j	        v rt          d| j	        z            t!          | j	                                                  d         | _        |pi | _        || _        |	| _        t-          j                    | _        d | _        |#|                    d          \  | _        }| _        t9          | j        d          | _        t=          j        | j                  | _         i | _!        d S )Nr?   context	remote_ipprotocolhttpHostr   z	127.0.0.1zMissing Host headerzInvalid Host header: %rrl   z%Multiple host headers not allowed: %rr   ?Tkeep_blank_values)"r6   r   r   rN   r   r   getattrr   r   r7   KeyErrorrn   r   rm   printr,   split_host_and_portlower	host_namer   r   r   time_start_time_finish_time	partitionpathqueryr   	argumentsr   deepcopyquery_argumentsbody_arguments)rS   r6   r   r   r   r   r   r   r   r   r   seps               r@   rT   zHTTPServerRequest.__init__  s    !#- FC/+--KC	 *i66 +t<<V<<	<V,DII 	< 	< 	<*$$'		$%:;;; 		< z##DI.. 	H%*$%%% !:TY!FGGG$)" !!H49!TUUU,TY__->->??B[b
$!29;; ?),s););&DIsDJ'
dKKK#}T^<< s   :B 'B76B7c                 J   t          | d          st          j                                        | _        d| j        v ra	 t          | j        d                   }|                                D ] \  }}	 || j        |<   # t          $ r Y w xY wn# t          $ r Y nw xY w| j        S )z0A dictionary of ``http.cookies.Morsel`` objects._cookiesCookie)	hasattrr   cookiesSimpleCookier   r   parse_cookierx   	Exception)rS   parsedre   rf   s       r@   r   zHTTPServerRequest.cookies  s     tZ(( 	!))++ M 4<''!)$,x*@AAF !' ! !1!/0DM!,,( ! ! ! !D	!! !   D }s#   B 2
A==
B
	B

BBc                 6    | j         dz   | j        z   | j        z   S )z+Reconstructs the full URL for this request.z://)r   r7   r   r   s    r@   full_urlzHTTPServerRequest.full_url1  s    }u$ty048;;r?   c                 d    | j         t          j                    | j        z
  S | j         | j        z
  S )z?Returns the amount of time it took for this request to execute.)r   r   r   r   s    r@   request_timezHTTPServerRequest.request_time5  s0    $9;;!111$t'777r?   Fbinary_formc                     	 | j         dS | j         j        j                            |          S # t          $ r Y dS w xY w)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   )rS   r   s     r@   get_ssl_certificatez%HTTPServerRequest.get_ssl_certificate<  s`    *	&t?)0<<' =     	 	 	44	s   0 $0 
>>c                     t          | j                            dd          | j        | j        | j        | j                   | j                                        D ]3\  }}| j                            |g           	                    |           4d S )NContent-Typer   )
parse_body_argumentsr   rt   r   r   r   rx   r   
setdefaultextend)rS   re   rf   s      r@   _parse_bodyzHTTPServerRequest._parse_body[  s    L^R00IJL	
 	
 	
 '--// 	7 	7DAqN%%a,,33A6666	7 	7r?   c                 n     d}d                      fd|D                       } j        j         d| dS )N)r   r7   r6   r   r   r   z, c                 :    g | ]}| d t          |          S )=)r   )rG   nrS   s     r@   rI   z.HTTPServerRequest.__repr__.<locals>.<listcomp>i  s1    EEE!Q55q!1!155EEEr?   r"   r    )rJ   	__class__r#   )rS   attrsrW   s   `  r@   __repr__zHTTPServerRequest.__repr__g  sJ    MyyEEEEuEEEFF.)33D3333r?   )	NNr   NNNNNN)FrB   N)r#   r$   r%   r&   r   r   _body_futurer   r   rN   bytesr   r   objectrT   propertyr   r   Morselr   floatr   r   r   r   r   r   r>   r?   r@   r   r   s  s       Z Zx DE L !%!!)- $7;1537.2B! B!B! c]B! 	B!
 +&B! uoB! S$z"2234B! -.B! /0B! $F+B! 
B! B! B! B!H c4<#667    X,<# < < < <8e 8 8 8 8 #( 	tT5 	!   >
7 
7 
7 
74# 4 4 4 4 4 4r?   r   c                       e Zd ZdZdS )rn   zqException class for malformed HTTP requests or responses
    from remote sources.

    .. versionadded:: 4.0
    Nr#   r$   r%   r&   r>   r?   r@   rn   rn   m  s          	Dr?   rn   c                       e Zd ZdZdS )HTTPOutputErrorzJException class for errors in HTTP output.

    .. versionadded:: 4.0
    Nr   r>   r?   r@   r   r   w  s         
 	Dr?   r   c                   6    e Zd ZdZdeddddfdZdeddfd	ZdS )
HTTPServerConnectionDelegatez_Implement this interface to handle requests from `.HTTPServer`.

    .. versionadded:: 4.0
    server_connrequest_connr   rB   HTTPMessageDelegatec                     t                      )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`.
        NotImplementedError)rS   r   r   s      r@   start_requestz*HTTPServerConnectionDelegate.start_request  s     "###r?   Nc                     dS )zThis 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>   )rS   r   s     r@   on_closez%HTTPServerConnectionDelegate.on_close  	     	r?   )r#   r$   r%   r&   r   r  r  r>   r?   r@   r   r     sl         
$!$1A$	$ $ $ $F t      r?   r   c                       e Zd ZdZded         dedeed                  fdZde	deed                  fd	Z
dd
ZddZdS )r   z_Implement this interface to handle an HTTP request or response.

    .. versionadded:: 4.0
    r   r   ResponseStartLiner   rB   Nc                     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>   )rS   r   r   s      r@   headers_receivedz$HTTPMessageDelegate.headers_received  s	    " 	r?   chunkc                     dS )ziCalled when a chunk of data has been received.

        May return a `.Future` for flow control.
        Nr>   rS   r  s     r@   data_receivedz!HTTPMessageDelegate.data_received  s	    
 	r?   c                     dS )z6Called after the last chunk of data has been received.Nr>   r   s    r@   finishzHTTPMessageDelegate.finish  rU   r?   c                     dS )zCalled 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   s    r@   on_connection_closez'HTTPMessageDelegate.on_connection_close  r  r?   r   )r#   r$   r%   r&   r   rN   r   r   r  r   r  r  r  r>   r?   r@   r   r     s         AB  
)D/	"	   &5 Xio-F            r?   r   c            	       ^    e Zd ZdZ	 dded         dedee         ddfd	Zdeddfd
Z	ddZ
dS )r   zYApplications use this interface to write their responses.

    .. versionadded:: 4.0
    Nr   r	  r   r  rB   zFuture[None]c                     t                      )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.
        r  )rS   r   r   r  s       r@   write_headerszHTTPConnection.write_headers  s    , "###r?   c                     t                      )zWrites a chunk of body data.

        Returns a future for flow control.

        .. versionchanged:: 6.0

           The ``callback`` argument was removed.
        r  r  s     r@   writezHTTPConnection.write  s     "###r?   c                     t                      )z3Indicates that the last body data has been written.r  r   s    r@   r  zHTTPConnection.finish  s    !###r?   rQ   r   )r#   r$   r%   r&   r   rN   r   r   r  r  r  r>   r?   r@   r   r     s          "&	$ $AB$ $ 	$
 
$ $ $ $0	$5 	$^ 	$ 	$ 	$ 	$$ $ $ $ $ $r?   r   urlrW   .c           	      d   || S t          |           }t          |t                    r>t          |j        d          }|                    |                                           nt          |t                    st          |t                    r,t          |j        d          }|                    |           n1d	                    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   r\            )r   ra   dictr	   r   r   rx   listtupleformattype	TypeErrorr   r   )r  rW   
parsed_urlparsed_queryerrfinal_querys         r@   
url_concatr*    s(   & |
#J$ 
 !1TJJJDJJLL))))	D$		 :dE#:#:  !1TJJJD!!!!GNNJJ
 
 nnL))K
qMqMqMqMqM	
	 	C Jr?   c                   2    e Zd ZU dZeed<   eed<   eed<   dS )r   zRepresents a file uploaded via a form.

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

    * ``filename``
    * ``body``
    * ``content_type``
    filenamer   content_typeN)r#   r$   r%   r&   r   __annotations__r   r>   r?   r@   r   r   (  s<           MMM
KKKr?   r   range_headerc                 Z   |                      d          \  }}}|                                |                                }}|dk    rdS |                     d          \  }}}	 t          |          }t          |          }n# t          $ r Y dS w xY w|||dk    r| }d}n|dz  }||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   r   NrD   r   r\   )r   r   _int_or_noner   )r/  unit_ri   start_bend_br   ends           r@   _parse_request_ranger7  8  s    > "++C00ND!U**,,%Dwt,,GQW%%5!!   tt
=axx1HC3<s   $B 
BBr   r6  totalc                 .    | pd} |p|dz
  }d|  d| d| S )zReturns 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   r\   zbytes rD   /r>   )r   r6  r8  s      r@   _get_content_ranger;  k  s9     JQE<%1
C)E))C))%)))r?   valc                 X    |                                  } | dk    rd S t          |           S )Nr   )r   r   )r<  s    r@   r1  r1  z  s(    
))++C
byyts88Or?   r-  r   r   r   r   c                    |                      d          r|rd|v rt          d|d         z            	 t          |d          }n%# t          $ r}t          d|z            |d}~ww xY w|                                D ]0\  }}|r)|                    |g                               |           1dS |                      d          r|rd|v rt          d|d         z            	 |                     d	          }	|	D ]W}
|
                                	                    d
          \  }}}|dk    r$|r"t          t          |          |||            dS Xt          d          # t          $ r}t          d|z            |d}~ww xY w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: %sTr   z&Invalid x-www-form-urlencoded body: %sNzmultipart/form-data;r   boundaryzmultipart boundary not foundzInvalid multipart/form-data: %s)
startswithrn   r   r   rx   r   r   rK   r   r   parse_multipart_form_datar   )r-  r   r   r   r   uri_argumentserA   ry   fieldsfieldre   r   rf   s                 r@   r   r     s    BCC O 	)W44 2W=O5PP  	V*44HHHMM 	V 	V 	V !IA!MNNTUU	V)//11 	> 	>LD& >$$T2..55f===	> 	> 
	 	 !6	7	7 O 	)W44 2W=O5PP  
	O!'',,F E E!KKMM33C88	3
??q?-d1ggtYNNNEE$%CDDD 	O 	O 	O !BQ!FGGQN	OO Os6   A 
A)A$$A)'A,E% E% %
F/FFr@  datac                 *   |                      d          r|                     d          r
| dd         } |                    d| z   dz             }|dk    rt          d          |d|                             d| z   dz             }|D ]}|s|                    d          }|dk    rt          d	          t                              |d|                             d
          d          }|	                    dd          }	t          |	          \  }
}|
dk    s|                    d          st          d          ||dz   d         }|	                    d          st          d          |d         }|	                    d          rW|	                    dd          }|                    |g                               t          |d         ||                     ^|                    |g                               |           d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.
       "r\   r}   s   --z4Invalid multipart/form-data: no final boundary foundNs   
s   

z#multipart/form-data missing headerszutf-8Frg   zContent-Dispositionr   z	form-datazInvalid multipart/form-data   rA   z multipart/form-data missing namer,  r   zapplication/unknown)r,  r   r-  )rA  endswithrfindrn   rK   r   rN   r   decodert   _parse_headerr   rq   r   )r@  rG  r   r   final_boundary_indexpartsparteohr   disp_headerdispositiondisp_paramsri   rA   ctypes                  r@   rB  rB    sD   , 4   "X%6%6t%<%< "AbD>::eh&6&>??r!!STTT&&&'--eh.>.HIIE 9 9 	ii$$"99 !FGGG##D#J$5$5g$>$>QV#WWkk"7<<#0#=#= [+%%T]]7-C-C% !>???S1Wr\"v&& 	E !CDDD6"??:&& 	9KK0EFFET2&&--(45u        r**11%8888/9 9r?   tsc                    t          | t          t          f          r| }nt          | t          t          j        f          rt          j        |           }nSt          | t          j                  r't          j        | 	                                          }nt          d| z            t          j                            |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. Naive `datetime.datetime` objects are assumed to represent
    UTC; aware objects are converted to UTC before formatting.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    zunknown timestamp type: %rT)usegmt)ra   r   r   r"  r   struct_timecalendartimegmdatetimeutctimetupler%  emailutils
formatdate)rX  time_nums     r@   format_timestamprd    s     "sEl## ;	B 01	2	2 ;?2&&	B)	*	* ;?2??#4#4554r9:::;!!(4!888r?   c                   .    e Zd ZU eed<   eed<   eed<   dS )r   r6   r   r   N)r#   r$   r%   r   r.  r>   r?   r@   r   r     s+         KKK
IIILLLLLr?   r   rz   c                 \   t           j                            |           }|st          d          t	          |                    d          |                    d          |                    d                    }|j                            d          st          d|j        z            |S )zReturns a (method, path, version) tuple for an HTTP 1.x request line.

    The response is a `typing.NamedTuple`.

    >>> parse_request_start_line("GET /foo HTTP/1.1")
    RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
    zMalformed HTTP request liner\   r  r  HTTP/1Unexpected HTTP version %r)r   r;   rm   rn   r   groupr   rA  rz   matchrs      r@   parse_request_start_linerm    s     ((..E < :;;;QQQHHA9)) G 9AIEFFFHr?   c                   .    e Zd ZU eed<   eed<   eed<   dS )r
  r   codereasonN)r#   r$   r%   r   r.  r   r>   r?   r@   r
  r
    s+         LLL
IIIKKKKKr?   r
  c                 v   t           j                            |           }|st          d          t	          |                    d          t          |                    d                    |                    d                    }|j                            d          st          d|j        z            |S )zReturns a (version, code, reason) tuple for an HTTP 1.x response line.

    The response is a `typing.NamedTuple`.

    >>> parse_response_start_line("HTTP/1.1 200 OK")
    ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
    z!Error parsing response start liner\   r  r  rg  rh  )	r   r=   rm   rn   r
  ri  r   r   rA  rj  s      r@   parse_response_start_linerr    s     ''--E B@AAA%++a..#ekk!nn*=*=u{{1~~NNA9)) G9AIEFFFHr?   sc              #     K   | d d         dk    r| dd          } |                      d          }|dk    r|                     dd|          |                     dd|          z
  dz  rQ|                      d|dz             }|dk    r2|                     dd|          |                     dd|          z
  dz  Q|dk     rt          |           }| d |         }|                                V  | |d          } | d d         dk    d S d S )Nr\   r?  r   "z\"r  )r   countr`   r   )rs  r6  fs      r@   _parseparamrx  9  s     
BQB%3,,abbEffSkkAgg17733//!''%C2H2HHAMg&&cAg&&C Agg17733//!''%C2H2HHAMg77a&&CdsdGggiicddG BQB%3,,,,,,r?   c                    t          d| z             }t          |          }dg}|D ]}|                    d          }|dk    rq|d|                                                                         }||dz   d                                         }|                    |t          |          f           t          j        	                    |          }|
                    d           i }	|D ]^\  }}
t          j                            |
          }t          |          dk    r"|d         dk    r|d	         dk    r
|dd	         }||	|<   _||	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?  )Dummyri   r   r   Nr\   r  ru  r}   )rx  nextr   r   r   rq   r
   r`  ra  decode_paramspopcollapse_rfc2231_valuer`   )rz   rQ  keyparamspirA   ri   decoded_paramspdictdecoded_values              r@   rO  rO  F  sO    d
##E
u++C !F 5 5FF3KK66RaR5;;==&&((Da!eggJ$$&&EMM4E!2!23444[..v66NqE-  m22=AAu::??uQx3593C3C!B$KEd:r?   r  r  c                     |s| S | g}t          |                                          D ]7\  }}||                    |           |                    | d|            8d                    |          S )zInverse 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'
    Nr   z; )sortedrx   rq   rJ   )r  r  outre   rf   s        r@   _encode_headerr  i  s      
%Cu{{}}%% # #19JJqMMMM JJ!zzazz""""99S>>r?   usernamepasswordc                     t          | t                    rt          j        d|           } t          |t                    rt          j        d|          }t	          |           dz   t	          |          z   S )zEncodes 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   :)ra   r   unicodedata	normalizer   )r  r  s     r@   encode_username_passwordr  }  sh     (L)) :(99(L)) :(99>>D 4>>11r?   c                  2    dd l } |                                 S )Nr   )doctestDocTestSuite)r  s    r@   doctestsr    s    NNN!!!r?   z^(.+):(\d+)$netlocc                     t                               |           }|r8|                    d          }t          |                    d                    }n| }d}||fS )zReturns ``(host, port)`` tuple from ``netloc``.

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

    .. versionadded:: 4.1
    r\   r  N)
_netloc_rerk  ri  r   )r  rk  r7   ports       r@   r   r     s[     V$$E {{1~~5;;q>>""$<r?   qsc              #   T   K   |                                  D ]\  }}|D ]}||fV  	dS )zgGenerator converting a result of ``parse_qs`` back to name-value pairs.

    .. versionadded:: 5.0
    N)rx   )r  re   vsrf   s       r@   	qs_to_qslr    sP      
   2 	 	Aa&LLLL	 r?   z\\(?:([0-3][0-7][0-7])|(.))r   c                 h    | d         r#t          t          | d         d                    S | d         S )Nr\      r  )chrr   )r   s    r@   _unquote_replacer    s1    t 3qtQ<<   tr?   c                     | t          |           dk     r| S | d         dk    s| d         dk    r| S | dd         } t          t          |           S )zHandle double quotes and escaping in cookie values.

    This method is copied verbatim from the Python 3.13 standard
    library (http.cookies._unquote) so we don't have to depend on
    non-public interfaces.
    Nr  r   ru  r}   r\   )r`   _unquote_subr  )rs  s    r@   _unquote_cookier    s\     	yCFFQJJts{{aesll 	
!B$A (!,,,r?   cookiec                     i }|                      d          D ]b}d|v r|                     dd          \  }}nd|}}|                                |                                }}|s|rt          |          ||<   c|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   r\   r   )rK   r   r  )r  
cookiedictr  r  r<  s        r@   r   r     s     Jc"" 
3 
3%<<{{3**HC 5C99;;		S 	3# 	3-c22JsOr?   rQ   )br&   r\  collections.abccollectionsr   r^  email.utilsr`  	functoolsr   http.clientr   http.cookiesr   r'   sslr   r   r  urllib.parser   r   r   r	   tornado.escaper
   r   r   r   tornado.utilr   r   r   r   r   r   r   r   r   r   r   r   r   r   TYPE_CHECKINGr   asyncior   unittestabcMutableMappingr   StrMutableMappingr   r(   ro   r   rL   rN   r   r   rn   r   r   r   r   r*  r   r   r7  r;  r1  r   r   rB  r   r"  r[  rd  
NamedTupler   rm  r
  rr  rx  rO  r  r  r  r  r   r  subr  Matchr  r  r   r>   r?   r@   <module>r     s|                      ! ! ! ! ! !     				            C C C C C C C C C C C C G G G G G G G G G G G G 1 1 1 1 1 1 1 1
 
	                           
 	7OOO $6sCx@#6  (RZ(KLL 5 5 5 5 5 5 5 5p 4?C ?C ? ? ? ?` ` ` ` `# ` ` `Fw4 w4 w4 w4 w4 w4 w4 w4t	 	 	 	 	Y 	 	 		 	 	 	 	i 	 	 	       :+ + + + + + + +\+$ +$ +$ +$ +$ +$ +$ +$\,	,
d38nd5c?3U5c?C;O5PP,
 	, , , ,^    z    00eHSM8C=0120 0 0 0f*hsm *(3- * *PS * * * *c hsm     &*+O +O+O
+O Ce$%+O T(^#$	+O
 k"+O 
+O +O +O +O\3939
39 Ce$%39 T(^#$	39
 
39 39 39 39l9c5%!183DDE99 9 9 90    v(   3 +;    ,    )   C ,=    4
3 
9S$_5 
 
 
 
   c4S>&9 :        F DcN s    (2CJ2+0e+<2
2 2 2 2 " " " RZ((
 c8C=.@(A    "$sDL() huS&[7I.J     rz899= S    -s -s - - - -6 c3h      r?   