a
    õ£Beþ>  ã                   @   s  d Z ddlZddlZddlmZ ddlmZmZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZ dd	lmZ 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 ejr²ddlmZ G dd„ deee	jƒZG dd„ de	jƒZG dd„ de ƒZ!G dd„ de	jƒZ"e	j#Z$dS )a¼  A non-blocking, single-threaded HTTP server.

Typical applications have little direct interaction with the `HTTPServer`
class except to start a server at the beginning of the process
(and even that is often done indirectly via `tornado.web.Application.listen`).

.. versionchanged:: 4.0

   The ``HTTPRequest`` class that used to live in this module has been moved
   to `tornado.httputil.HTTPServerRequest`.  The old name remains as an alias.
é    N)Ú
native_str)ÚHTTP1ServerConnectionÚHTTP1ConnectionParameters)Úhttputil)Úiostream)Únetutil)Ú	TCPServer)ÚConfigurable)	ÚUnionÚAnyÚDictÚCallableÚListÚTypeÚTupleÚOptionalÚ	Awaitable)ÚSetc                   @   s  e Zd ZdZeeddœdd„Zdeeje	ej
gdf f eeeeeeef ejf  ee eee ee ee ee ee ee eee  ddœdd	„Zeee d
œdd„ƒZeee d
œdd„ƒZdd
œdd„Zejeddœdd„Zeej ej!dœdd„Z"eddœdd„Z#dS )Ú
HTTPServeraÖ  A non-blocking, single-threaded HTTP server.

    A server is defined by a subclass of `.HTTPServerConnectionDelegate`,
    or, for backwards compatibility, a callback that takes an
    `.HTTPServerRequest` as an argument. The delegate is usually a
    `tornado.web.Application`.

    `HTTPServer` supports keep-alive connections by default
    (automatically for HTTP/1.1, or for HTTP/1.0 when the client
    requests ``Connection: keep-alive``).

    If ``xheaders`` is ``True``, we support the
    ``X-Real-Ip``/``X-Forwarded-For`` and
    ``X-Scheme``/``X-Forwarded-Proto`` headers, which override the
    remote IP and URI scheme/protocol for all requests.  These headers
    are useful when running Tornado behind a reverse proxy or load
    balancer.  The ``protocol`` argument can also be set to ``https``
    if Tornado is run behind an SSL-decoding proxy that does not set one of
    the supported ``xheaders``.

    By default, when parsing the ``X-Forwarded-For`` header, Tornado will
    select the last (i.e., the closest) address on the list of hosts as the
    remote host IP address.  To select the next server in the chain, a list of
    trusted downstream hosts may be passed as the ``trusted_downstream``
    argument.  These hosts will be skipped when parsing the ``X-Forwarded-For``
    header.

    To make this server serve SSL traffic, send the ``ssl_options`` keyword
    argument with an `ssl.SSLContext` object. For compatibility with older
    versions of Python ``ssl_options`` may also be a dictionary of keyword
    arguments for the `ssl.wrap_socket` method.::

       ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
       ssl_ctx.load_cert_chain(os.path.join(data_dir, "mydomain.crt"),
                               os.path.join(data_dir, "mydomain.key"))
       HTTPServer(application, ssl_options=ssl_ctx)

    `HTTPServer` initialization follows one of three patterns (the
    initialization methods are defined on `tornado.tcpserver.TCPServer`):

    1. `~tornado.tcpserver.TCPServer.listen`: single-process::

            async def main():
                server = HTTPServer()
                server.listen(8888)
                await asyncio.Event.wait()

            asyncio.run(main())

       In many cases, `tornado.web.Application.listen` can be used to avoid
       the need to explicitly create the `HTTPServer`.

       While this example does not create multiple processes on its own, when
       the ``reuse_port=True`` argument is passed to ``listen()`` you can run
       the program multiple times to create a multi-process service.

    2. `~tornado.tcpserver.TCPServer.add_sockets`: multi-process::

            sockets = bind_sockets(8888)
            tornado.process.fork_processes(0)
            async def post_fork_main():
                server = HTTPServer()
                server.add_sockets(sockets)
                await asyncio.Event().wait()
            asyncio.run(post_fork_main())

       The ``add_sockets`` interface is more complicated, but it can be used with
       `tornado.process.fork_processes` to run a multi-process service with all
       worker processes forked from a single parent.  ``add_sockets`` can also be
       used in single-process servers if you want to create your listening
       sockets in some way other than `~tornado.netutil.bind_sockets`.

       Note that when using this pattern, nothing that touches the event loop
       can be run before ``fork_processes``.

    3. `~tornado.tcpserver.TCPServer.bind`/`~tornado.tcpserver.TCPServer.start`:
       simple **deprecated** multi-process::

            server = HTTPServer()
            server.bind(8888)
            server.start(0)  # Forks multiple sub-processes
            IOLoop.current().start()

       This pattern is deprecated because it requires interfaces in the
       `asyncio` module that have been deprecated since Python 3.10. Support for
       creating multiple processes in the ``start`` method will be removed in a
       future version of Tornado.

    .. versionchanged:: 4.0
       Added ``decompress_request``, ``chunk_size``, ``max_header_size``,
       ``idle_connection_timeout``, ``body_timeout``, ``max_body_size``
       arguments.  Added support for `.HTTPServerConnectionDelegate`
       instances as ``request_callback``.

    .. versionchanged:: 4.1
       `.HTTPServerConnectionDelegate.start_request` is now called with
       two arguments ``(server_conn, request_conn)`` (in accordance with the
       documentation) instead of one ``(request_conn)``.

    .. versionchanged:: 4.2
       `HTTPServer` is now a subclass of `tornado.util.Configurable`.

    .. versionchanged:: 4.5
       Added the ``trusted_downstream`` argument.

    .. versionchanged:: 5.0
       The ``io_loop`` argument has been removed.
    N)ÚargsÚkwargsÚreturnc                 O   s   d S ©N© )Úselfr   r   r   r   úU/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/tornado/httpserver.pyÚ__init__œ   s    zHTTPServer.__init__F)Úrequest_callbackÚno_keep_aliveÚxheadersÚssl_optionsÚprotocolÚdecompress_requestÚ
chunk_sizeÚmax_header_sizeÚidle_connection_timeoutÚbody_timeoutÚmax_body_sizeÚmax_buffer_sizeÚtrusted_downstreamr   c              	   C   sR   || _ || _|| _t||||	p d||
|d�| _tj| |||d� tƒ | _|| _	d S )Ni  )Ú
decompressr#   r$   Zheader_timeoutr'   r&   r   )r    r(   Zread_chunk_size)
r   r   r!   r   Úconn_paramsr   r   ÚsetÚ_connectionsr)   )r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r   r   r   Ú
initialize¤   s(    ù	üzHTTPServer.initialize©r   c                 C   s   t S r   ©r   ©Úclsr   r   r   Úconfigurable_baseÐ   s    zHTTPServer.configurable_basec                 C   s   t S r   r0   r1   r   r   r   Úconfigurable_defaultÔ   s    zHTTPServer.configurable_defaultc                 Ã   s(   | j r$tt| j ƒƒ}| ¡ I dH  q dS )a&  Close all open connections and asynchronously wait for them to finish.

        This method is used in combination with `~.TCPServer.stop` to
        support clean shutdowns (especially for unittests). Typical
        usage would call ``stop()`` first to stop accepting new
        connections, then ``await close_all_connections()`` to wait for
        existing connections to finish.

        This method does not currently close open websocket connections.

        Note that this method is a coroutine and must be called with ``await``.

        N)r-   ÚnextÚiterÚclose)r   Úconnr   r   r   Úclose_all_connectionsØ   s    z HTTPServer.close_all_connections)ÚstreamÚaddressr   c                 C   s:   t ||| j| jƒ}t|| j|ƒ}| j |¡ | | ¡ d S r   )Ú_HTTPRequestContextr!   r)   r   r+   r-   ÚaddÚstart_serving)r   r:   r;   Úcontextr8   r   r   r   Úhandle_streamë   s    ÿzHTTPServer.handle_stream)Úserver_connÚrequest_connr   c                 C   s>   t | jtjƒr| j ||¡}nt| j|ƒ}| jr:t||ƒ}|S r   )Ú
isinstancer   r   ÚHTTPServerConnectionDelegateÚstart_requestÚ_CallableAdapterr   Ú_ProxyAdapter)r   rA   rB   Údelegater   r   r   rE   ó   s    
zHTTPServer.start_request)rA   r   c                 C   s   | j  t t|¡¡ d S r   )r-   ÚremoveÚtypingÚcastr   )r   rA   r   r   r   Úon_close   s    zHTTPServer.on_close)FFNNFNNNNNNN)$Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r
   r   rD   r   ÚHTTPServerRequestÚboolr   r   ÚstrÚsslÚ
SSLContextÚintÚfloatr   r.   Úclassmethodr   r	   r3   r4   r9   r   ÚIOStreamr   r@   ÚobjectÚHTTPConnectionÚHTTPMessageDelegaterE   rL   r   r   r   r   r   .   sX   m            ïÿÿ
î,	þr   c                   @   sˆ   e Zd Zeejgdf ejddœdd„Zeej	ej
f ej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 )rF   N)r   rB   r   c                 C   s"   || _ || _d | _d | _g | _d S r   )Ú
connectionr   ÚrequestrH   Ú_chunks)r   r   rB   r   r   r   r     s
    z_CallableAdapter.__init__©Ú
start_lineÚheadersr   c                 C   s"   t j| jt t j|¡|d�| _d S )N)r]   ra   rb   )r   rQ   r]   rJ   rK   ÚRequestStartLiner^   ©r   ra   rb   r   r   r   Úheaders_received  s    ýz!_CallableAdapter.headers_received©Úchunkr   c                 C   s   | j  |¡ d S r   )r_   Úappend©r   rg   r   r   r   Údata_received  s    z_CallableAdapter.data_receivedr/   c                 C   s8   | j d usJ ‚d | j¡| j _| j  ¡  |  | j ¡ d S )Nó    )r^   Újoinr_   ÚbodyZ_parse_bodyr   ©r   r   r   r   Úfinish   s    
z_CallableAdapter.finishc                 C   s   | ` d S r   )r_   rn   r   r   r   Úon_connection_close&  s    z$_CallableAdapter.on_connection_close)rM   rN   rO   r   r   rQ   r[   r   r
   rc   ÚResponseStartLineÚHTTPHeadersr   r   re   Úbytesrj   ro   rp   r   r   r   r   rF     s   ü
ürF   c                   @   s`   e Zd Zdejeee eee  ddœdd„Z	edœdd„Z
ejddœd	d
„Zddœdd„ZdS )r<   N)r:   r;   r!   r)   r   c                 C   s–   || _ |jd ur|jj| _nd | _| jtjtjfv rH|d urH|d | _nd| _|rZ|| _nt|t	j
ƒrnd| _nd| _| j| _| j| _t|pŒg ƒ| _d S )Nr   z0.0.0.0ÚhttpsÚhttp)r;   ÚsocketÚfamilyÚaddress_familyÚAF_INETÚAF_INET6Ú	remote_ipr!   rC   r   ZSSLIOStreamÚ_orig_remote_ipÚ_orig_protocolr,   r)   )r   r:   r;   r!   r)   r   r   r   r   +  s$    
ÿþz_HTTPRequestContext.__init__r/   c                 C   s<   | j tjtjfv r| jS t| jtƒr.t| jƒS t	| jƒS d S r   )
rx   rv   ry   rz   r{   rC   r;   rs   r   rS   rn   r   r   r   Ú__str__M  s
    
z_HTTPRequestContext.__str__)rb   r   c                 C   s”   |  d| j¡}dd„ t| d¡ƒD ƒD ]}|| jvr& q:q&|  d|¡}t |¡rV|| _|  d|  d| j¡¡}|r‚| d¡d  ¡ }|d	v r�|| _d
S )z2Rewrite the ``remote_ip`` and ``protocol`` fields.zX-Forwarded-Forc                 s   s   | ]}|  ¡ V  qd S r   )Ústrip)Ú.0Úcandr   r   r   Ú	<genexpr>]  rk   z6_HTTPRequestContext._apply_xheaders.<locals>.<genexpr>ú,z	X-Real-IpzX-SchemezX-Forwarded-Protoéÿÿÿÿ)ru   rt   N)	Úgetr{   ÚreversedÚsplitr)   r   Zis_valid_ipr!   r   )r   rb   ÚipZproto_headerr   r   r   Ú_apply_xheadersX  s    

ÿz#_HTTPRequestContext._apply_xheadersc                 C   s   | j | _| j| _dS )z›Undo changes from `_apply_xheaders`.

        Xheaders are per-request so they should not leak to the next
        request on the same connection.
        N)r|   r{   r}   r!   rn   r   r   r   Ú_unapply_xheadersn  s    z%_HTTPRequestContext._unapply_xheaders)N)rM   rN   rO   r   rY   r   r   rS   r   r   r~   r   rr   r‰   rŠ   r   r   r   r   r<   *  s    û
ú"r<   c                   @   sŒ   e Zd Zejejddœdd„Zeejej	f ej
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dœdd„ZdS )rG   N)rH   rB   r   c                 C   s   || _ || _d S r   )r]   rH   )r   rH   rB   r   r   r   r   y  s    z_ProxyAdapter.__init__r`   c                 C   s   | j j |¡ | j ||¡S r   )r]   r?   r‰   rH   re   rd   r   r   r   re   �  s    z_ProxyAdapter.headers_receivedrf   c                 C   s   | j  |¡S r   )rH   rj   ri   r   r   r   rj   ‹  s    z_ProxyAdapter.data_receivedr/   c                 C   s   | j  ¡  |  ¡  d S r   )rH   ro   Ú_cleanuprn   r   r   r   ro   Ž  s    
z_ProxyAdapter.finishc                 C   s   | j  ¡  |  ¡  d S r   )rH   rp   r‹   rn   r   r   r   rp   ’  s    
z!_ProxyAdapter.on_connection_closec                 C   s   | j j ¡  d S r   )r]   r?   rŠ   rn   r   r   r   r‹   –  s    z_ProxyAdapter._cleanup)rM   rN   rO   r   r\   r[   r   r
   rc   rq   rr   r   r   re   rs   rj   ro   rp   r‹   r   r   r   r   rG   x  s   ü

ü
rG   )%rP   rv   rT   Ztornado.escaper   Ztornado.http1connectionr   r   Útornador   r   r   Ztornado.tcpserverr   Ztornado.utilr	   rJ   r
   r   r   r   r   r   r   r   r   ÚTYPE_CHECKINGr   rD   r   r\   rF   rZ   r<   rG   rQ   ZHTTPRequestr   r   r   r   Ú<module>   s&   , W&N"