U
    bh4                     @  sl  d Z ddlmZ ddlZddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZ ddlmZ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 ddlmZ ddlmZ ddlmZm Z  ddl!m"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.m/Z/m0Z0 dgZ1dddddZ2dddddZ3G dd dZ4G dd dZ5dddd d!Z6G d"d dZ7dS )#z
Telnet server.
    )annotationsN)get_running_loop)AnyCallable	CoroutineTextIOcast)create_app_sessionget_app)run_in_terminal)Size)AnyFormattedTextto_formatted_text)	PipeInputcreate_pipe_input)Vt100_Output)print_formatted_text)	BaseStyle
DummyStyle   )logger)DOECHOIACLINEMODEMODENAWSSBSESENDSUPPRESS_GO_AHEADTTYPEWILLTelnetProtocolParserTelnetServerintbytes)numberreturnc                 C  s
   t | fS N)r&   )r'    r*   H/tmp/pip-unpacked-wheel-9s95tbmv/prompt_toolkit/contrib/telnet/server.pyint2byte,   s    r,   socket.socketNone)
connectionr(   c                 C  s   t d | tt t  | tt t  | tt t t	 t
d t t  | tt t  | tt t  | tt t  | tt t t t t  d S )NzInitializing telnet connectionr   )r   infosendr   r   r   r"   r    r   r   r,   r   r   r   r!   r   r/   r*   r*   r+   _initialize_telnet0   s    
&r3   c                   @  s   e Zd ZdZddddddZdddd	d
ZddddZddddZddddZe	ddddZ
e	ddddZdS )_ConnectionStdoutzk
    Wrapper around socket which provides `write` and `flush` methods for the
    Vt100_Output output.
    r-   strr.   )r/   encodingr(   c                 C  s"   || _ || _d| _g | _d| _d S )NstrictF)	_encoding_connection_errors_buffer_closed)selfr/   r6   r*   r*   r+   __init__S   s
    z_ConnectionStdout.__init__datar(   c                 C  s2   | dd}| j|j| j| jd |   d S )N
z
)errors)replacer;   appendencoder8   r:   flushr=   r@   r*   r*   r+   writeZ   s    z_ConnectionStdout.writeboolr(   c                 C  s   dS NTr*   r=   r*   r*   r+   isatty_   s    z_ConnectionStdout.isattyc              
   C  s\   z| j s| jd| j W n2 tk
rP } ztd|  W 5 d }~X Y nX g | _d S )N    z Couldn't send data over socket: )r<   r9   r1   joinr;   OSErrorr   warning)r=   er*   r*   r+   rF   b   s    "z_ConnectionStdout.flushc                 C  s
   d| _ d S rK   )r<   rL   r*   r*   r+   closek   s    z_ConnectionStdout.closec                 C  s   | j S r)   )r8   rL   r*   r*   r+   r6   n   s    z_ConnectionStdout.encodingc                 C  s   | j S r)   )r:   rL   r*   r*   r+   rB   r   s    z_ConnectionStdout.errorsN)__name__
__module____qualname____doc__r>   rH   rM   rF   rS   propertyr6   rB   r*   r*   r*   r+   r4   M   s   	r4   c                   @  s   e Zd ZdZd%ddddddd	d
dd	ddZddddZdddddZddddZdddddZdddddZ	dddd d!Z
ddd"d#Zd$S )&TelnetConnectionz6
    Class that represents one Telnet connection.
    Tr-   ztuple[str, int]7Callable[[TelnetConnection], Coroutine[Any, Any, None]]r$   r5   BaseStyle | Noner   rI   r.   )	connaddrinteractserverr6   stylevt100_input
enable_cprr(   c	                   s   |_ |_|_|_|_|_d_t _	|_
 _d _tddd_t| ddfddttt||d	_d
ddfdd}	ddddfdd}
ddd fdd}t|	|
|_d _d S )NF(   O   rowscolumnsr   rJ   c                     s    j S r)   )sizer*   rL   r*   r+   get_size   s    z+TelnetConnection.__init__.<locals>.get_size)r6   r&   r.   r?   c                   s    j |  dS )z-TelnetProtocolParser 'data_received' callbackN)ra   Z
send_bytesr@   rL   r*   r+   data_received   s    z0TelnetConnection.__init__.<locals>.data_receivedr%   )rf   rg   r(   c                   s2   t | |d _ jdk	r. jr. jdd  dS )z-TelnetProtocolParser 'size_received' callbackre   Nc                   S  s
   t   S r)   )r
   Z
_on_resizer*   r*   r*   r+   <lambda>   rN   zBTelnetConnection.__init__.<locals>.size_received.<locals>.<lambda>)r   rh   vt100_outputcontextrunre   rL   r*   r+   size_received   s    z0TelnetConnection.__init__.<locals>.size_receivedr5   )ttyper(   c                   s"   t j|  d_j  dS )z.TelnetProtocolParser 'ttype_received' callback)Ztermrb   N)r   stdoutrm   _readyset)rq   rb   ri   r=   r*   r+   ttype_received   s       z1TelnetConnection.__init__.<locals>.ttype_received)r\   r]   r^   r_   r6   r`   r<   asyncioEventrs   ra   rb   rm   r   rh   r3   r   r   r4   rr   r#   parserrn   )r=   r\   r]   r^   r_   r6   r`   ra   rb   rk   rp   rv   r*   ru   r+   r>   |   s(    
zTelnetConnection.__init__rJ   c              	     s   dd fdd}t  }| j| zJ j I dH  t j jd  t	
  _  I dH  W 5 Q R X W 5    X dS )z"
        Run application.
        r.   rJ   c                    s:    j d} | r |  ntdj j     d S )Ni   z&Connection closed by client. {!r} {!r})r\   recvfeedr   r0   formatr]   rS   rj   rL   r*   r+   handle_incoming_data   s
    z>TelnetConnection.run_application.<locals>.handle_incoming_dataN)inputoutput)r   
add_readerr\   rS   rs   waitr	   ra   rm   contextvarsZcopy_contextrn   r^   )r=   r}   Zloopr*   rL   r+   run_application   s    

z TelnetConnection.run_applicationr&   r?   c                 C  s   | j | dS )zF
        Handler for incoming data. (Called by TelnetServer.)
        N)ry   r{   rG   r*   r*   r+   r{      s    zTelnetConnection.feedc                 C  s<   | j s8d| _ | j  t | j | j  | j  dS )z#
        Closed by client.
        TN)r<   ra   rS   r   remove_readerr\   rr   rL   r*   r*   r+   rS      s    

zTelnetConnection.closer   )formatted_textr(   c                 C  s0   | j dkrdS t|}t| j || jp(t  dS )z*
        Send text to the client.
        N)rm   r   r   r`   r   r=   r   r*   r*   r+   r1      s    
  
zTelnetConnection.sendc                   s   t    fddS )z\
        Send text to the client.
        This is asynchronous, returns a `Future`.
        c                     s
     S r)   )r1   r*   r   r=   r*   r+   rl      rN   z4TelnetConnection.send_above_prompt.<locals>.<lambda>)r   _run_in_terminalr   r*   r   r+   send_above_prompt   s    z"TelnetConnection.send_above_promptzCallable[[], None])funcr(   c                 C  s"   | j r| j t| ntdd S )Nz2Called _run_in_terminal outside `run_application`.)rn   ro   r   RuntimeError)r=   r   r*   r*   r+   r      s    z!TelnetConnection._run_in_terminalc                 C  s4   | j dkrdS | j   | j dd | j   dS )zB
        Erase the screen and move the cursor to the top.
        Nr   )rm   erase_screenZcursor_gotorF   rL   r*   r*   r+   r      s
    

zTelnetConnection.erase_screenN)T)rT   rU   rV   rW   r>   r   r{   rS   r1   r   r   r   r*   r*   r*   r+   rY   w   s     7rY   c                   s   d S r)   r*   r2   r*   r*   r+   _dummy_interact  s    r   c                	   @  s   e Zd ZdZddedddfddd	dd
dddddZeddddddZd dddddZddddZ	ddddZ
dddddZdS )!r$   a  
    Telnet server implementation.

    Example::

        async def interact(connection):
            connection.send("Welcome")
            session = PromptSession()
            result = await session.prompt_async(message="Say something: ")
            connection.send(f"You said: {result}
")

        async def main():
            server = TelnetServer(interact=interact, port=2323)
            await server.run()
    z	127.0.0.1   zutf-8NTr5   r%   rZ   r[   rI   r.   )hostportr^   r6   r`   rb   r(   c                 C  s<   || _ || _|| _|| _|| _|| _d | _g | _t | _	d S r)   )
r   r   r^   r6   r`   rb   	_run_task_application_tasksrt   connections)r=   r   r   r^   r6   r`   rb   r*   r*   r+   r>     s    zTelnetServer.__init__r-   )r   r   r(   c                 C  s>   t  t jt j}|t jt jd |||f |d |S )Nr      )socketAF_INETSOCK_STREAM
setsockopt
SOL_SOCKETSO_REUSEADDRbindlisten)clsr   r   sr*   r*   r+   _create_socket2  s
    
zTelnetServer._create_socketzCallable[[], None] | None)ready_cbr(   c                   s      j jtd j j t  fdd |rD|  zt I dH  W 5 t     j	D ]}|
  qrt j	dkrtj j	dtjdI dH  X dS )z
        Run the telnet server, until this gets cancelled.

        :param ready_cb: Callback that will be called at the point that we're
            actually listening.
        z.Listening for telnet connections on %s port %rc                     s
     S r)   )_acceptr*   r=   r   r*   r+   rl   H  rN   z"TelnetServer.run.<locals>.<lambda>r   N)timeoutZreturn_when)r   r   r   r   r0   r   r   r   rS   r   cancellenrw   r   ZALL_COMPLETEDZFuture)r=   r   tr*   r   r+   ro   <  s*      

zTelnetServer.runrJ   c                 C  s$   | j dk	rdS t |  | _ dS )z}
        Deprecated: Use `.run()` instead.

        Start the telnet server (stop by calling and awaiting `stop()`).
        N)r   r   create_taskro   rL   r*   r*   r+   startc  s    
zTelnetServer.startc                   s@   | j dk	r<| j   z| j I dH  W n tjk
r:   Y nX dS )z
        Deprecated: Use `.run()` instead.

        Stop a telnet server that was started using `.start()` and wait for the
        cancellation to complete.
        N)r   r   rw   ZCancelledErrorrL   r*   r*   r+   stopo  s    

zTelnetServer.stop)listen_socketr(   c                   sP   |  \ tjd   dd fdd}t | j dS )z1
        Accept new incoming connection.
        New connection %r %rr.   rJ   c                    s  zzt p} t jjj| jd}j	| t
jd   z| I d H  W 5 j| t
jd	   X W 5 Q R X W n tk
r   t
d Y nf tk
r   t
d Y nJ tk
r } z*tdt|j | dd l}|  W 5 d }~X Y nX W 5 j  X d S )
N)r6   r`   ra   rb   Starting interaction %r %rStopping interaction %r %rz)Unhandled EOFError in telnet application.z2Unhandled KeyboardInterrupt in telnet application.zGot r   )r   )r   )r   remover   rY   r^   r6   r`   rb   r   addr   r0   r   EOFErrorKeyboardInterruptBaseExceptionprinttyperT   	traceback	print_exc)ra   r/   rR   r   r]   r\   r=   Ztaskr*   r+   ro     s6    
z!TelnetServer._accept.<locals>.runN)r   )acceptr   r0   r   r   r   rD   )r=   r   ro   r*   r   r+   r   }  s
    &zTelnetServer._accept)N)rT   rU   rV   rW   r   r>   classmethodr   ro   r   r   r   r*   r*   r*   r+   r$   
  s   	')8rW   
__future__r   rw   r   r   r   typingr   r   r   r   r   Z"prompt_toolkit.application.currentr	   r
   Z*prompt_toolkit.application.run_in_terminalr   Zprompt_toolkit.data_structuresr   Zprompt_toolkit.formatted_textr   r   Zprompt_toolkit.inputr   r   Zprompt_toolkit.output.vt100r   Zprompt_toolkit.rendererr   Zprompt_toolkit.stylesr   r   logr   protocolr   r   r   r   r   r   r   r   r   r    r!   r"   r#   __all__r,   r3   r4   rY   r   r$   r*   r*   r*   r+   <module>   s2   <* 