B
    h*3                 @   s   d 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	m
Z
 ddlmZmZ ddlmZmZ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 ejrddlmZmZ G dd deZ dS )z+A non-blocking, single-threaded TCP server.    N)gen)app_log)IOLoop)IOStreamSSLIOStream)bind_socketsadd_accept_handlerssl_wrap_socket)process)errno_from_exception)UnionDictAnyIterableOptional	Awaitable)CallableListc               @   s   e Zd ZdZd"eeeef ej	f e
e
ddddZd#e
edddd	Zeej dd
ddZejddddZdejddfe
eeje
eddddZd$ee
 e
ddddZddddZeeeed  dddZejeddd d!ZdS )%	TCPServera	  A non-blocking, single-threaded TCP server.

    To use `TCPServer`, define a subclass which overrides the `handle_stream`
    method. For example, a simple echo server could be defined like this::

      from tornado.tcpserver import TCPServer
      from tornado.iostream import StreamClosedError
      from tornado import gen

      class EchoServer(TCPServer):
          async def handle_stream(self, stream, address):
              while True:
                  try:
                      data = await stream.read_until(b"\n")
                      await stream.write(data)
                  except StreamClosedError:
                      break

    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"))
       TCPServer(ssl_options=ssl_ctx)

    `TCPServer` initialization follows one of three patterns:

    1. `listen`: simple single-process::

            server = TCPServer()
            server.listen(8888)
            IOLoop.current().start()

    2. `bind`/`start`: simple multi-process::

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

       When using this interface, an `.IOLoop` must *not* be passed
       to the `TCPServer` constructor.  `start` will always start
       the server on the default singleton `.IOLoop`.

    3. `add_sockets`: advanced multi-process::

            sockets = bind_sockets(8888)
            tornado.process.fork_processes(0)
            server = TCPServer()
            server.add_sockets(sockets)
            IOLoop.current().start()

       The `add_sockets` interface is more complicated, but it can be
       used with `tornado.process.fork_processes` to give you more
       flexibility in when the fork happens.  `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`.

    .. versionadded:: 3.1
       The ``max_buffer_size`` argument.

    .. versionchanged:: 5.0
       The ``io_loop`` argument has been removed.
    N)ssl_optionsmax_buffer_sizeread_chunk_sizereturnc             C   s   || _ i | _i | _g | _d| _d| _|| _|| _| j d k	rt| j t	rd| j krXt
dtj| j d s|td| j d  d| j krtj| j d std| j d  d S )NFcertfilez%missing key "certfile" in ssl_optionszcertfile "%s" does not existkeyfilezkeyfile "%s" does not exist)r   _sockets	_handlers_pending_sockets_started_stoppedr   r   
isinstancedictKeyErrorospathexists
ValueError)selfr   r   r    r(   NC:\Users\sanjo\AppData\Local\Qlobot\Launcher\ext_packages\tornado\tcpserver.py__init__l   s$    
zTCPServer.__init__ )portaddressr   c             C   s   t ||d}| | dS )a/  Starts accepting connections on the given port.

        This method may be called more than once to listen on multiple ports.
        `listen` takes effect immediately; it is not necessary to call
        `TCPServer.start` afterwards.  It is, however, necessary to start
        the `.IOLoop`.
        )r-   N)r   add_sockets)r'   r,   r-   socketsr(   r(   r)   listen   s    zTCPServer.listen)r/   r   c             C   s6   x0|D ](}|| j | < t|| j| j| < qW dS )a  Makes this server start accepting connections on the given sockets.

        The ``sockets`` parameter is a list of socket objects such as
        those returned by `~tornado.netutil.bind_sockets`.
        `add_sockets` is typically used in combination with that
        method and `tornado.process.fork_processes` to provide greater
        control over the initialization of a multi-process server.
        N)r   filenor   _handle_connectionr   )r'   r/   sockr(   r(   r)   r.      s    	
zTCPServer.add_sockets)socketr   c             C   s   |  |g dS )zASingular version of `add_sockets`.  Takes a single socket object.N)r.   )r'   r4   r(   r(   r)   
add_socket   s    zTCPServer.add_socket   F)r,   r-   familybacklog
reuse_portr   c             C   s4   t |||||d}| jr$| | n| j| dS )a&  Binds this server to the given port on the given address.

        To start the server, call `start`. If you want to run this server
        in a single process, you can call `listen` as a shortcut to the
        sequence of `bind` and `start` calls.

        Address may be either an IP address or hostname.  If it's a hostname,
        the server will listen on all IP addresses associated with the
        name.  Address may be an empty string or None to listen on all
        available interfaces.  Family may be set to either `socket.AF_INET`
        or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
        both will be used if available.

        The ``backlog`` argument has the same meaning as for
        `socket.listen <socket.socket.listen>`. The ``reuse_port`` argument
        has the same meaning as for `.bind_sockets`.

        This method may be called multiple times prior to `start` to listen
        on multiple ports or interfaces.

        .. versionchanged:: 4.4
           Added the ``reuse_port`` argument.
        )r-   r7   r8   r9   N)r   r   r.   r   extend)r'   r,   r-   r7   r8   r9   r/   r(   r(   r)   bind   s
    zTCPServer.bind   )num_processesmax_restartsr   c             C   s>   | j r
td| _ |dkr$t|| | j}g | _| | dS )a  Starts this server in the `.IOLoop`.

        By default, we run the server in this process and do not fork any
        additional child process.

        If num_processes is ``None`` or <= 0, we detect the number of cores
        available on this machine and fork that number of child
        processes. If num_processes is given and > 1, we fork that
        specific number of sub-processes.

        Since we use processes and not threads, there is no shared memory
        between any server code.

        Note that multiple processes are not compatible with the autoreload
        module (or the ``autoreload=True`` option to `tornado.web.Application`
        which defaults to True when ``debug=True``).
        When using multiple processes, no IOLoops can be created or
        referenced until after the call to ``TCPServer.start(n)``.

        The ``max_restarts`` argument is passed to `.fork_processes`.

        .. versionchanged:: 6.0

           Added ``max_restarts`` argument.
        Tr<   N)r   AssertionErrorr
   Zfork_processesr   r.   )r'   r=   r>   r/   r(   r(   r)   start   s    
zTCPServer.start)r   c             C   sR   | j r
dS d| _ x<| j D ].\}}| |ks4t| j|  |  qW dS )zStops listening for new connections.

        Requests currently in progress may still continue after the
        server is stopped.
        NT)r   r   itemsr1   r?   r   popclose)r'   fdr3   r(   r(   r)   stop   s    zTCPServer.stop)streamr-   r   c             C   s
   t  dS )ad  Override to handle a new `.IOStream` from an incoming connection.

        This method may be a coroutine; if so any exceptions it raises
        asynchronously will be logged. Accepting of incoming connections
        will not be blocked by this coroutine.

        If this `TCPServer` is configured for SSL, ``handle_stream``
        may be called before the SSL handshake has completed. Use
        `.SSLIOStream.wait_for_handshake` if you need to verify the client's
        certificate or use NPN/ALPN.

        .. versionchanged:: 4.2
           Added the option for this method to be a coroutine.
        N)NotImplementedError)r'   rF   r-   r(   r(   r)   handle_stream  s    zTCPServer.handle_stream)
connectionr-   r   c          
   C   s:  | j d k	rtstdyt|| j ddd}W n~ tjk
rj } z|jd tjkrX| S  W d d }~X Y nB tj	k
r } z"t
|tjtjfkr| S  W d d }~X Y nX yd| j d k	rt|| j| jd}nt|| j| jd}| ||}|d k	rt t|dd  W n$ tk
r4   tj	d	dd
 Y nX d S )Nz(Python 2.6+ and OpenSSL required for SSLTF)server_sidedo_handshake_on_connectr   )r   r   c             S   s   |   S )N)result)fr(   r(   r)   <lambda>G      z.TCPServer._handle_connection.<locals>.<lambda>zError in connection callback)exc_info)r   sslr?   r	   SSLErrorargsSSL_ERROR_EOFrC   r4   errorr   errnoECONNABORTEDEINVALr   r   r   r   rH   r   current
add_futurer   convert_yielded	Exceptionr   )r'   rI   r-   errrF   futurer(   r(   r)   r2     s@    



zTCPServer._handle_connection)NNN)r+   )r<   N)__name__
__module____qualname____doc__r   r   strr   rQ   
SSLContextintr*   r0   r   r4   r.   r5   	AF_UNSPECAddressFamilyboolr;   r   r@   rE   r   tupler   rH   r2   r(   r(   r(   r)   r   &   s$   D   "r   )!rb   rV   r#   r4   rQ   tornador   tornado.logr   tornado.ioloopr   Ztornado.iostreamr   r   tornado.netutilr   r   r	   r
   tornado.utilr   typingr   r   r   r   r   r   TYPE_CHECKINGr   r   objectr   r(   r(   r(   r)   <module>   s     