3
ò\ð]tq  ã               @   sŠ   d dl 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m
Z
 ddlmZ ddlmZ ejdƒZG d	d
„ d
eƒZdS )é    N)Úurllibé   )Ú
exceptions)Úpacket)Úpayload)Úsocketzengineio.serverc               @   s$  e Zd ZdZddgZdddgZdZdLdd„Zdd„ Zdd„ Z	dMdd„Z
dNdd„Zdd„ Zdd„ Zdd„ ZdOdd „Zd!d"„ Zd#d$„ Zd%d&„ ZdPd(d)„Zd*d+„ Zd,d-„ Zd.d/„ Zd0d1„ ZdQd2d3„Zd4d5„ Zd6d7„ Zd8d9„ ZdRd:d;„Zd<d=„ Zd>d?„ Zd@dA„ ZdBdC„ Z dDdE„ Z!dFdG„ Z"dHdI„ Z#dJdK„ Z$dS )SÚServeraC  An Engine.IO server.

    This class implements a fully compliant Engine.IO web server with support
    for websocket and long-polling transports.

    :param async_mode: The asynchronous model to use. See the Deployment
                       section in the documentation for a description of the
                       available options. Valid async modes are "threading",
                       "eventlet", "gevent" and "gevent_uwsgi". If this
                       argument is not given, "eventlet" is tried first, then
                       "gevent_uwsgi", then "gevent", and finally "threading".
                       The first async mode that has all its dependencies
                       installed is the one that is chosen.
    :param ping_timeout: The time in seconds that the client waits for the
                         server to respond before disconnecting. The default
                         is 60 seconds.
    :param ping_interval: The interval in seconds at which the client pings
                          the server. The default is 25 seconds. For advanced
                          control, a two element tuple can be given, where
                          the first number is the ping interval and the second
                          is a grace period added by the server. The default
                          grace period is 5 seconds.
    :param max_http_buffer_size: The maximum size of a message when using the
                                 polling transport. The default is 100,000,000
                                 bytes.
    :param allow_upgrades: Whether to allow transport upgrades or not. The
                           default is ``True``.
    :param http_compression: Whether to compress packages when using the
                             polling transport. The default is ``True``.
    :param compression_threshold: Only compress messages when their byte size
                                  is greater than this value. The default is
                                  1024 bytes.
    :param cookie: Name of the HTTP cookie that contains the client session
                   id. If set to ``None``, a cookie is not sent to the client.
                   The default is ``'io'``.
    :param cors_allowed_origins: Origin or list of origins that are allowed to
                                 connect to this server. Only the same origin
                                 is allowed by default. Set this argument to
                                 ``'*'`` to allow all origins, or to ``[]`` to
                                 disable CORS handling.
    :param cors_credentials: Whether credentials (cookies, authentication) are
                             allowed in requests to this server. The default
                             is ``True``.
    :param logger: To enable logging set to ``True`` or pass a logger object to
                   use. To disable logging set to ``False``. The default is
                   ``False``.
    :param json: An alternative json module to use for encoding and decoding
                 packets. Custom json modules must have ``dumps`` and ``loads``
                 functions that are compatible with the standard library
                 versions.
    :param async_handlers: If set to ``True``, run message event handlers in
                           non-blocking threads. To run handlers synchronously,
                           set to ``False``. The default is ``True``.
    :param monitor_clients: If set to ``True``, a background task will ensure
                            inactive clients are closed. Set to ``False`` to
                            disable the monitoring task (not recommended). The
                            default is ``True``.
    :param kwargs: Reserved for future extensions, any additional parameters
                   given as keyword arguments will be silently ignored.
    ÚgzipÚdeflateÚconnectÚ
disconnectÚmessageTNé<   é   é áõé   ÚioFc             K   s  || _ t|tƒr&|d | _|d | _n|| _d| _|| _|| _|| _|| _|| _	|	| _
|
| _|| _i | _i | _|d k	rz|n| j| _|d k	r’|tj_t|tƒs¤|| _nPt| _tjj rô| jjtjkrô|rÖ| jjtjƒ n| jjtjƒ | jjtjƒ ƒ | j ƒ }|d k	�r||k�r|gng }d | _!d | _"xp|D ]h}yJt#j$d| ƒj!| _!d| j!k�rZ| j!d nd}|| j%ƒ k�rp�w,|| _"P W n t&k
�r�   Y nX �q,W | j"d k�r¬t'dƒ‚| j%ƒ �rØd| j!k�sÐ| j!d  �rØt'dƒ‚| j%ƒ  �rd| j!k�r| j!d �rt'd	ƒ‚| jj(d
| j"ƒ d S )Nr   r   é   zengineio.async_drivers.ZasyncioFzInvalid async_mode specifiedz1The selected async_mode is not asyncio compatiblezKThe selected async_mode requires asyncio and must use the AsyncServer classzServer initialized for %s.))Úping_timeoutÚ
isinstanceÚtupleÚping_intervalZping_interval_grace_periodÚmax_http_buffer_sizeÚallow_upgradesÚhttp_compressionÚcompression_thresholdÚcookieÚcors_allowed_originsÚcors_credentialsÚasync_handlersÚsocketsÚhandlersÚ_default_monitor_clientsÚstart_service_taskr   ÚPacketÚjsonÚboolÚloggerÚdefault_loggerÚloggingÚrootÚlevelÚNOTSETÚsetLevelÚINFOÚERRORÚ
addHandlerÚStreamHandlerÚasync_modesÚ_asyncÚ
async_modeÚ	importlibÚimport_moduleÚis_asyncio_basedÚImportErrorÚ
ValueErrorÚinfo)Úselfr4   r   r   r   r   r   r   r   r   r   r'   r%   r   Zmonitor_clientsÚkwargsÚmodesÚmodeZasyncio_based© r?   ú:/tmp/pip-build-mqc4i71p/python-engineio/engineio/server.pyÚ__init__S   sl    






zServer.__init__c             C   s   dS )NFr?   )r;   r?   r?   r@   r7   —   s    zServer.is_asyncio_basedc             C   s   ddddgS )NZeventletZgevent_uwsgiZgeventÚ	threadingr?   )r;   r?   r?   r@   r2   š   s    zServer.async_modesc                s8   ˆ ˆj krtdƒ‚‡ ‡fdd„}|dkr,|S ||ƒ dS )aù  Register an event handler.

        :param event: The event name. Can be ``'connect'``, ``'message'`` or
                      ``'disconnect'``.
        :param handler: The function that should be invoked to handle the
                        event. When this parameter is not given, the method
                        acts as a decorator for the handler function.

        Example usage::

            # as a decorator:
            @eio.on('connect')
            def connect_handler(sid, environ):
                print('Connection request')
                if environ['REMOTE_ADDR'] in blacklisted:
                    return False  # reject

            # as a method:
            def message_handler(sid, msg):
                print('Received message: ', msg)
                eio.send(sid, 'response')
            eio.on('message', message_handler)

        The handler function receives the ``sid`` (session ID) for the
        client as first argument. The ``'connect'`` event handler receives the
        WSGI environment as a second argument, and can return ``False`` to
        reject the connection. The ``'message'`` handler receives the message
        payload as a second argument. The ``'disconnect'`` handler does not
        take a second argument.
        zInvalid eventc                s   | ˆj ˆ < | S )N)r!   )Úhandler)Úeventr;   r?   r@   Úset_handler¿   s    
zServer.on.<locals>.set_handlerN)Úevent_namesr9   )r;   rD   rC   rE   r?   )rD   r;   r@   Úon�   s    
z	Server.onc             C   sN   y| j |ƒ}W n" tk
r0   | jjd|ƒ dS X |jtjtj||d�ƒ dS )aZ  Send a message to a client.

        :param sid: The session id of the recipient client.
        :param data: The data to send to the client. Data can be of type
                     ``str``, ``bytes``, ``list`` or ``dict``. If a ``list``
                     or ``dict``, the data will be serialized as JSON.
        :param binary: ``True`` to send packet as binary, ``False`` to send
                       as text. If not given, unicode (Python 2) and str
                       (Python 3) are sent as text, and str (Python 2) and
                       bytes (Python 3) are sent as binary.
        zCannot send to sid %sN)ÚdataÚbinary)Ú_get_socketÚKeyErrorr'   ÚwarningÚsendr   r$   ZMESSAGE)r;   ÚsidrH   rI   r   r?   r?   r@   rM   Ç   s    zServer.sendc             C   s   | j |ƒ}|jS )aC  Return the user session for a client.

        :param sid: The session id of the client.

        The return value is a dictionary. Modifications made to this
        dictionary are not guaranteed to be preserved unless
        ``save_session()`` is called, or when the ``session`` context manager
        is used.
        )rJ   Úsession)r;   rN   r   r?   r?   r@   Úget_sessionÛ   s    

zServer.get_sessionc             C   s   | j |ƒ}||_dS )z�Store the user session for a client.

        :param sid: The session id of the client.
        :param session: The session dictionary.
        N)rJ   rO   )r;   rN   rO   r   r?   r?   r@   Úsave_sessionè   s    
zServer.save_sessionc                s   G ‡ fdd„dt ƒ}|| ˆ ƒS )aN  Return the user session for a client with context manager syntax.

        :param sid: The session id of the client.

        This is a context manager that returns the user session dictionary for
        the client. Any changes that are made to this dictionary inside the
        context manager block are saved back to the session. Example usage::

            @eio.on('connect')
            def on_connect(sid, environ):
                username = authenticate_user(environ)
                if not username:
                    return False
                with eio.session(sid) as session:
                    session['username'] = username

            @eio.on('message')
            def on_message(sid, msg):
                with eio.session(sid) as session:
                    print('received message from ', session['username'])
        c                   s,   e Zd Zdd„ Z‡ fdd„Z‡ fdd„ZdS )z0Server.session.<locals>._session_context_managerc             S   s   || _ || _d | _d S )N)ÚserverrN   rO   )r;   rR   rN   r?   r?   r@   rA     s    z9Server.session.<locals>._session_context_manager.__init__c                s   | j jˆ ƒ| _| jS )N)rR   rP   rO   )r;   )rN   r?   r@   Ú	__enter__  s    z:Server.session.<locals>._session_context_manager.__enter__c                s   | j jˆ | jƒ d S )N)rR   rQ   rO   )r;   Úargs)rN   r?   r@   Ú__exit__  s    z9Server.session.<locals>._session_context_manager.__exit__N)Ú__name__Ú
__module__Ú__qualname__rA   rS   rU   r?   )rN   r?   r@   Ú_session_context_manager  s   rY   )Úobject)r;   rN   rY   r?   )rN   r@   rO   ñ   s    zServer.sessionc             C   sp   |dk	rHy| j |ƒ}W n tk
r*   Y qlX |jƒ  || jkrl| j|= n$xtj| jƒD ]}|jƒ  qVW i | _dS )zªDisconnect a client.

        :param sid: The session id of the client to close. If this parameter
                    is not given, then all clients are closed.
        N)rJ   rK   Úcloser    ÚsixÚ
itervalues)r;   rN   r   Úclientr?   r?   r@   r     s    

zServer.disconnectc             C   s   | j |ƒjrdS dS )z×Return the name of the transport used by the client.

        The two possible values returned by this function are ``'polling'``
        and ``'websocket'``.

        :param sid: The session of the client.
        Ú	websocketÚpolling)rJ   Úupgraded)r;   rN   r?   r?   r@   Ú	transport+  s    zServer.transportc             C   s  | j g krf|jdƒ}|rf| j|ƒ}|dk	rf||krf| jj|d ƒ | jƒ }||d |d ƒ |d gS |d }tjj|jdd	ƒƒ}d
|kr–|d
 d nd}d}	d}
d}d|krÖ|d d dksÒ|d d j	ƒ dkrÖd}	d|k�rd}
yt
|d d ƒ}W n tttfk
�r   Y nX |
�r>|dk�r>| jjdƒ | jƒ }�n|dk�r`|dk�r¤|jddgƒd }|dk�r�|dk�r�| jjd|ƒ | jƒ }n| j||||	|ƒ}nº|| jk�rÈ| jjd|ƒ | jƒ }n–| j|ƒ}y2|j||ƒ}t|tƒ�rþ| j||	|d�}n|}W n6 tjk
�r:   || jk�r.| j|ƒ | jƒ }Y nX || jk�rB| j| j�rB| j|= nâ|dk�r|dk�s€|| jk�r˜| jjd|ƒ | jƒ }n~| j|ƒ}y|j|ƒ | j|d�}W nX tjk
�rò   || jk�ræ| j|ƒ | jƒ }Y n$   | jjdƒ | j|d�}Y nX n*|dk�r,| jƒ }n| jjd|ƒ | jƒ }t|tƒ�sX|�pVg S | j�rÞt|d ƒ| j k�rÞdd „ |jd!d	ƒj!d"ƒD ƒ}xL|D ]D}|| j"k�r–t#| d#| ƒ|d ƒ|d< |d  d$|fg7  < P �q–W | j$|ƒ}||d |d | ƒ |d gS )%a+  Handle an HTTP request from the client.

        This is the entry point of the Engine.IO application, using the same
        interface as a WSGI application. For the typical usage, this function
        is invoked by the :class:`Middleware` instance, but it can be invoked
        directly when the middleware is not used.

        :param environ: The WSGI environment.
        :param start_response: The WSGI ``start_response`` function.

        This function returns the HTTP response body to deliver to the client
        as a byte sequence.
        ÚHTTP_ORIGINNz is not an accepted origin.ÚstatusÚheadersÚresponseÚREQUEST_METHODÚQUERY_STRINGÚ rN   r   FÚb64Ú1ÚtrueTÚjzInvalid JSONP index numberÚGETrb   r`   r_   zInvalid transport %szInvalid session %s)rj   Újsonp_indexÚPOST)ro   zpost request handler errorÚOPTIONSzMethod %s not supportedc             S   s   g | ]}|j d ƒd jƒ ‘qS )ú;r   )ÚsplitÚstrip)Ú.0Úer?   r?   r@   ú
<listcomp>   s    z)Server.handle_request.<locals>.<listcomp>ZHTTP_ACCEPT_ENCODINGú,Ú_zContent-Encoding)%r   ÚgetÚ_cors_allowed_originsr'   r:   Ú_bad_requestr   ÚparseÚparse_qsÚlowerÚintr9   rK   Ú
IndexErrorrL   Ú_handle_connectr    rJ   Úhandle_get_requestr   ÚlistÚ_okr   ZEngineIOErrorr   ÚclosedZhandle_post_requestÚ	exceptionÚ_method_not_foundÚdictr   Úlenr   rs   Úcompression_methodsÚgetattrÚ_cors_headers)r;   ÚenvironÚstart_responseÚoriginÚallowed_originsÚrÚmethodÚqueryrN   rj   Zjsonpro   rb   r   ÚpacketsÚ	encodingsÚencodingZcors_headersr?   r?   r@   Úhandle_request5  s¬    




$


















zServer.handle_requestc             O   s    | j d |||d�}|jƒ  |S )ad  Start a background task using the appropriate async model.

        This is a utility function that applications can use to start a
        background task using the method that is compatible with the
        selected async mode.

        :param target: the target function to execute.
        :param args: arguments to pass to the function.
        :param kwargs: keyword arguments to pass to the function.

        This function returns an object compatible with the `Thread` class in
        the Python standard library. The `start()` method on this object is
        already called by this function.
        Úthread)ÚtargetrT   r<   )r3   Ústart)r;   rš   rT   r<   Úthr?   r?   r@   Ústart_background_task¬  s    zServer.start_background_taskr   c             C   s   | j d |ƒS )a  Sleep for the requested amount of time using the appropriate async
        model.

        This is a utility function that applications can use to put a task to
        sleep without having to worry about using the correct call for the
        selected async mode.
        Úsleep)r3   )r;   Úsecondsr?   r?   r@   rž   ¿  s    zServer.sleepc             O   s   | j d ||ŽS )zóCreate a queue object using the appropriate async model.

        This is a utility function that applications can use to create a queue
        without having to worry about using the correct call for the selected
        async mode.
        Úqueue)r3   )r;   rT   r<   r?   r?   r@   Úcreate_queueÉ  s    zServer.create_queuec             C   s
   | j d S )zÿReturn the queue empty exception for the appropriate async model.

        This is a utility function that applications can use to work with a
        queue without having to worry about using the correct call for the
        selected async mode.
        Zqueue_empty)r3   )r;   r?   r?   r@   Úget_queue_empty_exceptionÒ  s    z Server.get_queue_empty_exceptionc             O   s   | j d ||ŽS )zõCreate an event object using the appropriate async model.

        This is a utility function that applications can use to create an
        event without having to worry about using the correct call for the
        selected async mode.
        rD   )r3   )r;   rT   r<   r?   r?   r@   Úcreate_eventÛ  s    zServer.create_eventc             C   s
   t jƒ jS )zGenerate a unique session id.)ÚuuidÚuuid4Úhex)r;   r?   r?   r@   Ú_generate_idä  s    zServer._generate_idc             C   s,  | j rd| _ | j| jƒ | jƒ }tj| |ƒ}|| j|< tjtj	|| j
||ƒt| jd ƒt| jd ƒdœƒ}|j|ƒ | jd||dd�}	|	dkrª| j|= | jjdƒ | jƒ S |dkrÐ|j||ƒ}	|jrÌ| j|= |	S d|_d	}
| jrôd
| jd | fg}
y| j|jƒ |
||d�S  tjk
�r&   | jƒ S X d	S )z#Handle a client connection request.Fiè  )rN   ZupgradesZpingTimeoutZpingIntervalr   )Ú	run_asynczApplication rejected connectionr_   TNz
Set-Cookieú=)re   rj   ro   )r#   r�   Ú_service_taskr§   r   ZSocketr    r   r$   ZOPENÚ	_upgradesr€   r   r   rM   Ú_trigger_eventr'   rL   Ú_unauthorizedrƒ   r†   Ú	connectedr   r…   Úpollr   Z
QueueEmptyr|   )r;   rŽ   r�   rb   rj   ro   rN   ÚsZpktÚretre   r?   r?   r@   r‚   è  s>    


zServer._handle_connectc             C   s4   | j  s*| j|ƒjs*| jd dks*|dkr.g S dgS )z=Return the list of possible upgrades for a client connection.r_   N)r   rJ   ra   r3   )r;   rN   rb   r?   r?   r@   r«     s    zServer._upgradesc          	   O   sl   |j ddƒ}|| jkrh|r0| j| j| f|žŽ S y| j| |Ž S    | jj|d ƒ |dkrbdS Y nX dS )zInvoke an event handler.r¨   Fz handler errorr   N)Úpopr!   r�   r'   r‡   )r;   rD   rT   r<   r¨   r?   r?   r@   r¬     s    
zServer._trigger_eventc             C   sF   y| j | }W n tk
r*   tdƒ‚Y nX |jrB| j |= tdƒ‚|S )z-Return the socket object for a given session.zSession not foundzSession is disconnected)r    rK   r†   )r;   rN   r°   r?   r?   r@   rJ   )  s    zServer._get_socketc             C   s^   |dk	rL|dkrg }|r$|dg7 }n
|dg7 }d|t j|d�j||d�dœS ddgd
dœS dS )z$Generate a successful HTTP response.NúContent-Typeútext/plain; charset=UTF-8úapplication/octet-streamz200 OK)r•   )rj   ro   )rd   re   rf   ú
text/plains   OK)r³   r´   )r³   rµ   )r³   r¶   )r   ZPayloadÚencode)r;   r•   re   rj   ro   r?   r?   r@   r…   4  s    
z
Server._okc             C   s   ddgddœS )z+Generate a bad request HTTP error response.z400 BAD REQUESTúContent-Typeú
text/plains   Bad Request)rd   re   rf   )r¸   r¹   r?   )r;   r?   r?   r@   r|   F  s    zServer._bad_requestc             C   s   ddgddœS )z0Generate a method not found HTTP error response.z405 METHOD NOT FOUNDúContent-Typeú
text/plains   Method Not Found)rd   re   rf   )rº   r»   r?   )r;   r?   r?   r@   rˆ   L  s    zServer._method_not_foundc             C   s   ddgddœS )z,Generate a unauthorized HTTP error response.z401 UNAUTHORIZEDúContent-Typeú
text/plains   Unauthorized)rd   re   rf   )r¼   r½   r?   )r;   r?   r?   r@   r­   R  s    zServer._unauthorizedc             C   s¾   g }d|kr|d|kr||j dj|d |d d�ƒ d|kr||jd|d ƒjdƒd jƒ }|j dj||d jdƒd jƒ d�ƒ | jd krŒ|}n.| jd	krœd }nt| jtjƒr´| jg}n| j}|S )
Nzwsgi.url_schemeZ	HTTP_HOSTz{scheme}://{host})ÚschemeÚhostZHTTP_X_FORWARDED_HOSTZHTTP_X_FORWARDED_PROTOrx   r   Ú*)	ÚappendÚformatrz   rs   rt   r   r   r\   Ústring_types)r;   rŽ   Zdefault_originsr¾   r‘   r?   r?   r@   r{   X  s&    



zServer._cors_allowed_originsc             C   sŠ   | j g krg S g }| j|ƒ}d|krF|dks8|d |krFd|d fg}|d dkr\|dg7 }d|krv|d	|d fg7 }| jr†|dg7 }|S )z1Return the cross-origin-resource-sharing headers.rc   NzAccess-Control-Allow-Originrg   rq   úAccess-Control-Allow-MethodsúOPTIONS, GET, POSTZ#HTTP_ACCESS_CONTROL_REQUEST_HEADERSzAccess-Control-Allow-Headersú Access-Control-Allow-Credentialsrl   )rÄ   rÅ   )rÆ   rl   )r   r{   r   )r;   rŽ   re   r‘   r?   r?   r@   r�   n  s     



zServer._cors_headersc          	   C   s4   t jƒ }tj|dd��}|j|ƒ W dQ R X |jƒ S )z%Apply gzip compression to a response.Úw)Úfileobjr>   N)r\   ÚBytesIOr	   ÚGzipFileÚwriteÚgetvalue)r;   rf   ZbytesioÚgzr?   r?   r@   Ú_gzip‚  s    zServer._gzipc             C   s
   t j|ƒS )z(Apply deflate compression to a response.)ÚzlibÚcompress)r;   rf   r?   r?   r@   Ú_deflate‰  s    zServer._deflatec             C   s¶   x°t | jƒdkr| j| jƒ qt| jƒt | jƒ }y>x8| jjƒ jƒ D ]&}|j r`|j r`|j	ƒ  | j|ƒ qDW W q t
tfk
r–   | jjdƒ P Y q   | jjdƒ Y qX qW dS )z;Monitor connected clients and clean up those that time out.r   zservice task canceledzservice task exceptionN)rŠ   r    rž   r   ÚfloatÚcopyÚvaluesÚclosingr†   Zcheck_ping_timeoutÚ
SystemExitÚKeyboardInterruptr'   r:   r‡   )r;   Zsleep_intervalr°   r?   r?   r@   rª   �  s    zServer._service_task)Nr   r   r   TTr   r   NTFNTN)N)N)N)r   )FN)NNFN)%rV   rW   rX   Ú__doc__r‹   rF   r"   rA   r7   r2   rG   rM   rP   rQ   rO   r   rb   r˜   r�   rž   r¡   r¢   r£   r§   r‚   r«   r¬   rJ   r…   r|   rˆ   r­   r{   r�   rÎ   rÑ   rª   r?   r?   r?   r@   r      sP   <
     
?
*
	%

w

			 
)
r   )r	   r5   r)   r¤   rÏ   r\   Z	six.movesr   ri   r   r   r   r   Ú	getLoggerr(   rZ   r   r?   r?   r?   r@   Ú<module>   s   
