
    mg9                       U 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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mZmZmZmZ ddl
mZmZmZ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 m!Z! ddlm"Z"m#Z#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+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1 ddl2m3Z3m4Z4m5Z5 ddl2m6Z6m7Z7m8Z8 ddl2m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZA ddlBmCZCmDZDmEZE ddlBmFZFmGZGmHZH ddlBmIZImJZJ ddlBmKZKmLZL ddlBmMZM ddlNmOZO ddlPmQZQmRZR ddlPmSZSmTZT erddlUmVZVmWZW dd lUmXZX ej                  ZZee[e\f   e]d!<    e9eZd"d#      Z^ e9eZd$d%      Z_ ej                  d&      Za ebe      j                         D  ci c]"  \  } }eaj                  |       r| d'd  e\|      $ c}} Zeeej                         D  ci c]  \  } }|| 
 c}} Zfee[ege[e[f   Zheee@geeg   f      Zi G d( d)ee   eA      Zj G d* d+ejee         Zk G d, d-ejee         Zl G d. d/ejee         Zm G d0 d1emee         Zn G d2 d3emee         Zo G d4 d5emep         Zq G d6 d7emep         Zr G d8 d9emep         Zsyc c}} w c c}} w ):z SSH channel and session handlers    N)MappingProxyType)TYPE_CHECKINGAnyAnyStr	AwaitableCallable)DictGenericIterableListMappingOptional)SetTupleUnioncast   )	constants)DEFAULT_LANGEXTENDED_DATA_STDERR)MSG_CHANNEL_OPENMSG_CHANNEL_WINDOW_ADJUST)MSG_CHANNEL_DATAMSG_CHANNEL_EXTENDED_DATA)MSG_CHANNEL_EOFMSG_CHANNEL_CLOSEMSG_CHANNEL_REQUEST)MSG_CHANNEL_SUCCESSMSG_CHANNEL_FAILURE)OPEN_CONNECT_FAILEDPTY_OP_RESERVED
PTY_OP_END)"OPEN_REQUEST_X11_FORWARDING_FAILED)OPEN_REQUEST_PTY_FAILEDOPEN_REQUEST_SESSION_FAILED)SSHLineEditorChannelSSHLineEditorSession)	SSHLogger)ChannelOpenError
MaybeAwaitProtocolError)	TermModesTermSizeTermSizeArg)get_symbol_namesmap_handler_name)BooleanByteStringUInt32	SSHPacketSSHPacketHandler)
SSHSessionSSHClientSessionSSHServerSession)SSHTCPSessionSSHUNIXSessionSSHTunTapSession)SSHSessionFactorySSHClientSessionFactory)SSHTCPSessionFactorySSHUNIXSessionFactory)SSHTunTapSessionFactory)DataType)SSH_TUN_MODE_POINTTOPOINTSSH_TUN_UNIT_ANY)SSH_TUN_AF_INETSSH_TUN_AF_INET6)SSHConnectionSSHClientConnection)SSHServerConnection_const_dictPTY_   EXTENDED_DATA_   zSIG[^_]   c                      e Zd ZU dZ e e       d      Z e       Ze	e
   ed<    e       Ze	e
   ed<   dddej                  dee   d	ed
e
de
fdZedefd       ZdadZdej                  fdZdeee   ef   fdZ	 dbdee   d	eddfdZde
fdZde	e
   fdZde	e
   fdZdcdee   ddfdZdddZdddZ dddZ!dddZ"dddZ#dcdee   ddfdZ$de%d e&ddfd!Z'dcde%d e&ddfd"Z(ddd#Z)d$e*ddfd%Z+dee   ddfd&Z,d'e
d(e
d)e
d*e-e.e/      ddf
d+Z0d*e.e/   ded,e.e/   f   fd-Z1d$e-e.e/      ddfd.Z2d'e
d(e
d)e
d/e3ddf
d0Z4d1e
d2ed3eddfd4Z5d5e
d6e
d/e3ddfd7Z6d5e
d6e
d/e3ddfd8Z7d5e
d6e
d/e3ddfd9Z8d5e
d6e
d/e3ddfd:Z9d5e
d6e
d/e3ddfd;Z:d5e
d6e
d/e3ddfd<Z;d=e
d6e
d/e3ddfd>Z<d/e3de*fd?Z=e>e6e?e7e@e8eAe9eBe:eCe;eDe<eEe<iZFd@e%dAe%de3fdBZGd=e
dAe%ddfdCZHdDdEdFe%dAe%dGe*ddfdHZIdFe%dAe%dee*   fdIZJdddJZKdddKZLde*fdLZMdddMZNdcdNedOeOdeOfdPZPdQeOddfdRZQde*fdSZRde
fdTZS	 	 dedUee
   dVee
   ddfdWZTdcde/d e&ddfdXZU	 dcdYeVe/   d e&ddfdZZWddd[ZXddd\ZYddd]ZZde[eef   fd^Z\dee   fd_Z]dee   fd`Z^y)f
SSHChannelzParent class for SSH channelsMSG_CHANNEL__read_datatypes_write_datatypesconnrG   loopencodingerrorswindowmax_pktsizec                 X   || _         || _        d| _        d|i| _        |  |  |  |  i | _        d| _        d| _        d| _        d| _        d| _	        d| _
        d| _        g | _        d| _        d| _        || _        || _        || _        d| _        g | _        g | _        d| _        g | _        t/        j0                         | _        |j5                  |       | _        |j8                  j;                  d| j6                  z        | _        | j?                  ||       | jA                          y)	a  Initialize an SSH channel

           If encoding is set, data sent and received will be in the form
           of strings, converted on the wire to bytes using the specified
           encoding. If encoding is None, data sent and received must be
           provided as bytes.

           Window specifies the initial receive window size.

           Max_pktsize specifies the maximum length of a single data packet.

        N
connectionclosedr   Fstartingzchan=%d)context)!_conn_loop_session_extra_env_command
_subsystem_send_state
_send_chan_send_window_send_pktsize_send_paused	_send_buf_send_buf_len_recv_state_init_recv_window_recv_window_recv_pktsize_recv_paused	_recv_buf_request_queue_open_waiter_request_waitersasyncioEvent_close_eventadd_channel
_recv_chanlogger	get_child_loggerset_encodingset_write_buffer_limits)selfrU   rV   rW   rX   rY   rZ   s          0lib/python3.12/site-packages/asyncssh/channel.py__init__zSSHChannel.__init__]   s(     15

6:*6)=$&	'+)-#)-!""#!;=#!'"(.879ACAE<>#MMO)-)9)9$)?{{,,Y-1__6=, > 	(F+$$&    returnc                     | j                   S )z%A logger associated with this channel)r~   r   s    r   r|   zSSHChannel.logger   s     ||r   c                 6    | j                   J | j                   S )z*Return the connection used by this channel)r`   r   s    r   get_connectionzSSHChannel.get_connection   s     zz%%%zzr   c                     | j                   S )z*Return the event loop used by this channel)ra   r   s    r   get_loopzSSHChannel.get_loop   s     zzr   c                 2    | j                   | j                  fS )z(Return the encoding used by this channel)	_encoding_errorsr   s    r   get_encodingzSSHChannel.get_encoding   s     ~~t||++r   Nc                     || _         || _        |rA t        j                  |      |      | _         t        j
                  |      |      | _        yd| _        d| _        y)z Set the encoding on this channelN)r   r   codecsgetincrementalencoder_encodergetincrementaldecoder_decoder)r   rW   rX   s      r   r   zSSHChannel.set_encoding   s_     "6,,X6v> M 7,,X6v> M !DM DMr   c                     | j                   S )z5Return the configured receive window for this channel)ro   r   s    r   get_recv_windowzSSHChannel.get_recv_window   s     %%%r   c                     | j                   S )z1Return the legal read data types for this channel)rS   r   s    r   get_read_datatypeszSSHChannel.get_read_datatypes   s     ###r   c                     | j                   S )z2Return the legal write data types for this channel)rT   r   s    r   get_write_datatypeszSSHChannel.get_write_datatypes   s     $$$r   excc                 L   | j                   rJ| j                   j                         s)| j                   j                  t        t        d             d| _         | j
                  rN| j
                  D ]8  }|j                         r|r|j                  |       (|j                  d       : g | _        | j                  "| j                  j                  |       d| _        | j                  j                          | j                  r| j                  dk(  r| j                  j                  d|rdt        |      z   nd       | j                  j!                  |        | j"                  J | j                  j%                  | j"                         d| _        d| _        d| _        yyy)zClean up this channelSSH connection closedNFr]   zChannel closed%sz:  )ru   	cancelledset_exceptionr)   r    rv   
set_resultrb   connection_lostry   setr`   rn   r|   infostrdetach_x11_listenerr{   remove_channelrh   )r   r   waiters      r   _cleanupzSSHChannel._cleanup   s\    $$..0!!//$%8%<>? !%D  //''),,S1))%0 0 %'D!==$MM))#. DM::$**h6KK/03TCH_= JJ**40??...JJ%%doo6"DO"DODJ 7:r   c                     g | _         d| _        | j                  dk7  r$| j                  t               d| _        d| _        yy)z5Discard unsent data and close the channel for sendingr   r]   N)rl   rm   rg   send_packetr   rh   r   s    r   _close_sendzSSHChannel._close_send   sD     x'./"DO'D (r   c                     g | _         d| _        | j                  dk(  rd| _        | j                  j	                  | j
                         y)z6Discard unreceived data and clean up if close receivedFclose_pendingr]   N)rs   rr   rn   ra   	call_soonr   r   s    r   _discard_recvzSSHChannel._discard_recv   sA     ! .'D

T]]+r   c                    K   | j                   dk(  r3| j                  j                  d       d| _         | j                          yyw)z)Start processing data on a new connectionr^   zReading from channel startedFNrr   r|   debug2_flush_recv_bufr   s    r   _start_readingzSSHChannel._start_reading  sB      
*KK=> %D  " +s   AAc                    | j                   re| j                  | j                  k  rK| j                  j	                  d       d| _         | j
                  J | j
                  j                          yy| j                  | j                  kD  rK| j                  j	                  d       d| _         | j
                  J | j
                  j                          yy)zAPause or resume writing based on send buffer low/high water markszWriting from session resumedFNzWriting from session pausedT)	rk   rm   _send_low_waterr|   r   rb   resume_writing_send_high_waterpause_writingr   s    r   _pause_resume_writingz SSHChannel._pause_resume_writing  s     !!T%9%99""#AB$)!}}000,,. : !!D$9$99""#@A$(!}}000++- :r   c                    | j                   r| j                  rt        | j                  | j                        }| j                   d   \  }}t	        |      |kD  r|d| }|d|= n|}| j                   d= | xj
                  t	        |      z  c_        | xj                  t	        |      z  c_        | | j                  t        t        |             n)| j                  t        t        |      t        |             | j                   r| j                  r| j                          | j                   sM| j                  dk(  r| j                  t               d| _        y| j                  dk(  r| j                          yyy)z;Flush as much data in send buffer as the send window allowsr   Neof_pendingeofr   )rl   ri   minrj   lenrm   r   r   r3   r   r4   r   rg   r   r   )r   pktsizebufdatatypedatas        r   _flush_send_bufzSSHChannel._flush_send_buf*  sC    nn!2!2$++T-?-?@G NN1-MC3x'!8G}MNN1%#d)+T*  !16$<@  !:!'!16$<A# nn!2!2( 	""$~~=0  1#( !!_4  " 5	 r   c                    | j                   rM| j                  sA | j                  | j                   j                  d        | j                   r| j                  sA| j                   s| j                  dk7  r| j                  r;|s9| j
                  dv r+	 | j                  J | j                  j                  dd       | j
                  dk(  rNd| _        | j                  J | j                  j                         s| j                  d	k(  r| j                          | j                   s>| j
                  d
k(  r.d| _        | j                  j!                  | j"                  |       yyy# t        $ r}t        t        |            dd}~ww xY w)z?Flush as much data in the recv buffer as the application allowsr   r^   )r   r   Nr   Tr   r   openr   r]   )rs   rr   _deliver_datapopr   rn   r   decodeUnicodeDecodeErrorr+   r   rb   eof_receivedrg   	write_eofra   r   r   )r   r   unicode_excs      r   r   zSSHChannel._flush_recv_bufJ  sM    nnT%6%6D 2 21 56 nnT%6%6 ~~$"3"3z"A~~c$$(HHD==444MM((d3 =0#( }}000224((F2NN$~~$"2"2o"E'DJJ  4 #F~ * D'K(89tCDs   *E$ $	F-FFr   r   c                    | xj                   t        |      z  c_         | j                   | j                  dz  k  rp| j                  | j                   z
  }| j                  j	                  d|| j                         | j                  t        t        |             | j                  | _         | j                  r9	 | j                  J t        t        | j                  j                  |            }nt        t        |      }| j                   | j                   j#                  ||       yy# t        $ r}t        t        |            dd}~ww xY w)z$Deliver incoming data to the session   z0Sending window adjust of %d bytes, new window %dN)rp   r   ro   r|   r   r   r   r4   r   r   r   r   r   r   r+   r   rb   data_received)r   r   r   adjustdecoded_datar   s         r   r   zSSHChannel._deliver_dataf  s    	SY&t5599++d.?.??FKK  /068N8NP 6vG $ 6 6D>>@}}000#FDMM,@,@,FG  -L==$MM''h? % & @#C$454?@s   87D* *	E3EEc                     |sy| j                   dv ry| j                  r| j                  j                  ||f       y| j	                  ||       y)aX  Accept new data on the channel

           This method accepts new data on the channel, immediately
           delivering it to the session if it hasn't paused reading.
           If it has paused, data is buffered until reading is resumed.

           Data sent after the channel has been closed by the session
           is dropped.

        N>   r]   r   )rg   rr   rs   appendr   )r   r   r   s      r   _accept_datazSSHChannel._accept_data  sL     ::NN!!4"23tX.r   c                 D   | j                   d   \  }}}dt        |      z   dz   }t        t        t	        | |d            }|r-| j
                  rt        t        t            ||            }n!d}n| j                  j                  d|       d}|| j                  |       yy)z*Process next item on channel request queuer   	_process__requestNTz$Received unknown channel request: %sF)rt   r0   r   _RequestHandlergetattrrb   r   boolr|   debug1_report_response)r   requestpacket_namehandlerresults          r   _service_next_requestz SSHChannel._service_next_request  s     "003-g66CdD(AB}}htngfo> KKEwOF!!&) r   r   c                 r   | j                   j                  d      \  }}}|r;| j                  dvr-|r| j                  t               n| j                  t
               |r<|dv r8| j                  J | j                  j                          | j                          | j                   r| j                          yy)z?Report back the response to a previously issued channel requestr   >   r]   r   >   execshell	subsystemN)
rt   r   rg   r   r   r   rb   session_startedresume_readingr   )r   r   r   r   
want_replys        r   r   zSSHChannel._report_response  s     "&!4!4!8!8!;J$**2MM  !45  !45g!??==,,,MM))+!&&( r   c                     | j                   j                  d       d| _        | j                          | j	                  |       y)z"Process the SSH connection closingz'Closing channel due to connection closer]   N)r|   r   rg   r   r   )r   r   s     r   process_connection_closez#SSHChannel.process_connection_close  s7     	BC#cr   	send_chansend_windowsend_pktsizesessionc                     || _         || _        || _        | j                  j	                  d||       | j
                  J | j
                  j                  | j                  |      | j                         y)zProcess a channel open request(  Initial send window %d, packet size %dN)rh   ri   rj   r|   r   r`   create_task_finish_open_request)r   r   r   r   r   s        r   process_openzSSHChannel.process_open  sj     $')E&	6 zz%%%

t88A4;;Or   zSSHChannel[AnyStr]c                 
    | |fS )z3Hook to optionally wrap channel and session objects )r   r   s     r   _wrap_sessionzSSHChannel._wrap_session  s    
 W}r   c                   K   	 t        j                  |      r't        t        t        t
              |       d{   }nt        t        t
           |      }| j                  st        t        d      | j                  |      \  }| _
        | j                  j                  d| j                  | j                         | j                  J | j                   J | j                  j#                  | j                  | j                   | j                  | j                         d| _        d| _        | j                  j)                  |       y7 # t        $ r}| j                  rT| j                  J | j                  j+                  | j                  |j,                  |j.                  |j0                         | j2                  j5                  | j6                         Y d}~yd}~ww xY ww)z(Finish processing a channel open requestNr   (  Initial recv window %d, packet size %dr   )inspectisawaitabler   r   r7   r   r`   r)   r    r   rb   r|   r   rp   rq   rh   r{   send_channel_open_confirmationrg   rn   connection_madesend_channel_open_failurecodereasonlangra   r   r   )r   r   r   chanr   s        r   r   zSSHChannel._finish_open_request  s    !	0""6* $Yz&/A%BF KKz&16:::&':'>@ @ #'"4"4W"=D$-KKI#00$2D2DF ??...??...JJ55doo6:oo6:6G6G6:6H6HJ
  &D%DMM))$/1 L2   	0zz222

44T__chh58ZZK JJ  //	0s@   G'6E E	DE G'	E 	G$BGG'G$$G'r   c                 *   | j                   st        d      || _        || _        || _        | j
                  j                  d||       d| _        d| _        | j                   j                         s| j                   j                  |       d| _         y)z#Process a channel open confirmationChannel not being openedr   r   N)ru   r+   rh   ri   rj   r|   r   rg   rn   r   r   )r   r   r   r   r   s        r   process_open_confirmationz$SSHChannel.process_open_confirmation  s        :;;#')E&	6 "!  **,((0 r   r  r  r  c                 
   | j                   st        d      | j                   j                         s&| j                   j                  t	        |||             d| _         | j
                  j                  | j                         y)zProcess a channel open failurer  N)ru   r+   r   r   r)   ra   r   r   )r   r  r  r  s       r   process_open_failurezSSHChannel.process_open_failure  sk        :;;  **,++ vt46 !

T]]+r   _pkttype_pktidc                    | j                   dvrt        d      |j                         }|j                          | xj                  |z  c_        | j
                  j                  d|| j                         | j                          y)z Process a send window adjustment>   r   r   r   Channel not openz1Received window adjust of %d bytes, new window %dN)rn   r+   
get_uint32	check_endri   r|   r   r   )r   r  r  r   r   s        r   _process_window_adjustz!SSHChannel._process_window_adjust'  s{     #AA 233""$V# +,2D4E4E	G 	r   c                 ,   | j                   dk7  rt        d      |j                         }|j                          t	        |      }|| j
                  kD  rt        d      | j                  j                  d||dkD  rdnd       | j                  |       y)	zProcess incoming datar   Channel not open for sendingWindow exceededzReceived %d data byte%sr   sr   N)	rn   r+   
get_stringr  r   rp   r|   r   r   )r   r  r  r   r   datalens         r   _process_datazSSHChannel._process_data8  s     v% >??  "d)T&&& 1224g")A+32	7 	$r   c                    | j                   dk7  rt        d      |j                         }|j                         }|j	                          || j
                  vrt        d      t        |      }|| j                  kD  rt        d      | j                  j                  d||dkD  rdndt        |          | j                  ||       y	)
zProcess incoming extended datar   r  Invalid extended data typer  zReceived %d data byte%s from %sr   r  r   N)rn   r+   r  r  r  rS   r   rp   r|   r   _data_type_namesr   )r   r  r  r   r   r   r  s          r   _process_extended_dataz!SSHChannel._process_extended_dataL  s     v% >??$$&  "4/// <==d)T&&& 122<g")A+32+H5	7 	$)r   c                     | j                   dk7  rt        d      |j                          | j                  j	                  d       d| _         | j                          y)zProcess an incoming end of filer   r  zReceived EOFr   N)rn   r+   r  r|   r   r   r   r  r  r   s       r   _process_eofzSSHChannel._process_eofe  sP     v% >??>*(r   c                     | j                   dvrt        d      |j                          | j                  j	                  d       | j                          d| _         | j                          y)z!Process an incoming channel close>   r   r   r   r  zReceived channel closer   N)rn   r+   r  r|   r   r   r   r  s       r   _process_closezSSHChannel._process_closes  s^     #AA 23312*r   c                 Z   | j                   dvrt        d      |j                         }|j                         }	 |j	                  d      }| j                  j                  |||f       t        | j                        dk(  r| j                          yy# t
        $ r t        d      dw xY w)z#Process an incoming channel request>   r   r   r   r  asciizInvalid channel requestNr   )
rn   r+   r  get_booleanr   r   rt   r   r   r   )r   r  r  r   request_bytesr   r   s          r   _process_requestzSSHChannel._process_request  s     #AA 233))+'')
	E#**73G 	""GVZ#@At""#q(&&( )	 " 	E 9:D	Es   B B*pkttypec                     |j                          | j                  rE| j                  j                  d      }|j                         s|j	                  |t
        k(         yyt        d      )z%Process a success or failure responser   zUnexpected channel responseN)r  rv   r   r   r   r   r+   )r   r(  r  r   r   s        r   _process_responsezSSHChannel._process_response  sb     	  **..q1F##%!!'-@"@A &   =>>r   c                 Z    |j                          | j                  j                  d       y)z-Process an incoming OpenSSH keepalive requestz*Received OpenSSH keepalive channel requestF)r  r|   r   r   r   s     r   -_process_keepalive_at_openssh_dot_com_requestz8SSHChannel._process_keepalive_at_openssh_dot_com_request  s&     	GHr   chantypeargsc           	        K   | j                   dk7  rt        d      | j                  j                         | _        | j
                  j                  d| j                  | j                         | j                  J | j                  J  | j                  j                  t        t        |      t        | j                        t        | j                        t        | j                        g|d| i | j                   d{   S 7 w)z"Make a request to open the channelr]   zChannel already openr   Nr   )rg   OSErrorra   create_futureru   r|   r   rp   rq   r`   r{   r   r   r3   r4   )r   r.  r/  s      r   _openzSSHChannel._open  s      x'011 JJ446E,,d.@.@	B zz%%%***

/1A%doo6%d&7&78%d&8&89	P =A	P KO	P
 &&&&&s   D D	DD	c                     | j                   yt        | j                         dj                  |      z   }| j                  J | j                  j	                  |||        y)zSend a packet on the channelNr   )r   )rh   r4   joinr`   r   )r   r(  r/  payloads       r   r   zSSHChannel.send_packet  sU     ??")CHHTN:zz%%%

w>r   F)r   r   r   c                Z     | j                   t        t        |      t        |      g|  y)zSend a channel requestN)r   r   r3   r1   )r   r   r   r/  s       r   _send_requestzSSHChannel._send_request  s-     	,fWo ,	5/3	5r   c                    K   | j                   y| j                  j                         }| j                  j	                  |        | j
                  |g|ddi | d{   S 7 w)z0Make a channel request and wait for the responseNFr   T)rh   ra   r2  rv   r   r8  )r   r   r/  r   s       r   _make_requestzSSHChannel._make_request  s_      ??"))+$$V,7;T;d;||s   AA' A%!A'c                     | j                   j                  d       | j                  dvr| j                          | j                  dk7  r| j                          yy)zForcibly close the channel

           This method can be called to forcibly close the channel, after
           which no more data can be sent or received. Any unsent buffered
           data and any incoming data in flight will be discarded.

        zAborting channel>   r]   r   r]   N)r|   r   rg   r   rn   r   r   s    r   abortzSSHChannel.abort  sQ     	+,#>>x'  (r   c                     | j                   j                  d       | j                  dvrd| _        | j                          | j                  dk7  r| j                          yy)a  Cleanly close the channel

           This method can be called to cleanly close the channel, after
           which no more data can be sent or received. Any unsent buffered
           data will be flushed asynchronously before the channel is
           closed.

        zClosing channel>   r]   r   r   r]   N)r|   r   rg   r   rn   r   r   s    r   closezSSHChannel.close  sY     	*+#>>.D  "x'  (r   c                      | j                   dk7  S )z-Return if the channel is closing or is closedr   )rg   r   s    r   
is_closingzSSHChannel.is_closing  s     6))r   c                 T   K   | j                   j                          d{    y7 w)zWait for this channel to close

           This method is a coroutine which can be called to block until
           this channel has finished closing.

        N)ry   waitr   s    r   wait_closedzSSHChannel.wait_closed  s       $$&&&s   (&(r   defaultc                     | j                   j                  || j                  r | j                  j                  ||            S |      S )ao  Get additional information about the channel

           This method returns extra information about the channel once
           it is established. Supported values include `'connection'`
           to return the SSH connection this channel is running over plus
           all of the values supported on that connection.

           For TCP channels, the values `'local_peername'` and
           `'remote_peername'` are added to return the local and remote
           host and port information for the tunneled TCP connection.

           For UNIX channels, the values `'local_peername'` and
           `'remote_peername'` are added to return the local and remote
           path information for the tunneled UNIX domain socket connection.
           Since UNIX domain sockets provide no "source" address, only
           one of these will be filled in.

           See :meth:`get_extra_info() <SSHClientConnection.get_extra_info>`
           on :class:`SSHClientConnection` for more information.

           Additional information stored on the channel by calling
           :meth:`set_extra_info` can also be returned here.

        )rc   getr`   get_extra_info)r   r   rD  s      r   rG  zSSHChannel.get_extra_info!  sE    4 {{t"&** &*ZZ%>%>tW%M ; 	;29; 	;r   kwargsc                 <     | j                   j                  di | y)as  Store additional information associated with the channel

           This method allows extra information to be associated with the
           channel. The information to store should be passed in as
           keyword parameters and can later be returned by calling
           :meth:`get_extra_info` with one of the keywords as the name
           to retrieve.

        Nr   )rc   update)r   rH  s     r   set_extra_infozSSHChannel.set_extra_info>  s     	$V$r   c                      y)znReturn whether the channel supports :meth:`write_eof`

           This method always returns `True`.

        Tr   r   s    r   can_write_eofzSSHChannel.can_write_eofK  s     r   c                     | j                   S )zReturn the current size of the channel's output buffer

           This method returns how many bytes are currently in the
           channel's output buffer waiting to be written.

        )rm   r   s    r   get_write_buffer_sizez SSHChannel.get_write_buffer_sizeU  s     !!!r   highlowc                     |	|d|z  nd}||dz  }d|cxk  r|k  sn t        d|d|d      | j                  j                  d||       || _        || _        | j                          y)	a  Set the high- and low-water limits for write flow control

           This method sets the limits used when deciding when to call
           the :meth:`pause_writing() <SSHClientSession.pause_writing>`
           and :meth:`resume_writing() <SSHClientSession.resume_writing>`
           methods on SSH sessions. Writing will be paused when the write
           buffer size exceeds the high-water mark, and resumed when the
           write buffer size equals or drops below the low-water mark.

        NrL   i   r   zhigh (z) must be >= low (z) must be >= 0z4Set write buffer limits: low-water=%d, high-water=%d)
ValueErrorr|   r   r   r   r   )r   rP  rQ  s      r   r   z"SSHChannel.set_write_buffer_limits_  s     <O1S5D;!)CC4"C) * * 	 +,/	7 !%"""$r   c                 4   | j                   dk7  rt        d      ||| j                  vrt        d      |sy| j                  r8| j
                  J | j
                  j                  t        t        |            }nt        t        |      }t        |      }|rdt        |   z  }nd}| j                  j                  d||dkD  rd	nd|       | j                  j                  t!        |      |f       | xj"                  |z  c_        | j%                          y)
a  Write data on the channel

           This method can be called to send data on the channel. If
           an encoding was specified when the channel was created, the
           data should be provided as a string and will be converted
           using that encoding. Otherwise, the data should be provided
           as bytes.

           An extended data type can optionally be provided. For
           instance, this is used from a :class:`SSHServerSession`
           to write data to `stderr`.

           :param data:
               The data to send on the channel
           :param datatype: (optional)
               The extended data type of the data, from :ref:`extended
               data types <ExtendedDataTypes>`
           :type data: `str` or `bytes`
           :type datatype: `int`

           :raises: :exc:`OSError` if the channel isn't open for sending
                    or the extended data type is not valid for this type
                    of channel

        r   r  Nr  z to %sr   zSending %d data byte%s%sr   r  )rg   BrokenPipeErrorrT   r1  r   r   encoder   r   bytesr   r  r|   r   rl   r   	bytearrayrm   r   )r   r   r   encoded_datar  typenames         r   writezSSHChannel.write}  s   6 v%!"@AAHD4I4I$I677>>==,,,==//S$@Lt,Ll#"28"<<HH5w")A+32x	A 	y6ABg%r   list_of_datac           	         | j                   r5t        t        dj                  t        t        t
           |                  }n4t        t        dj                  t        t        t           |                  }| j                  ||      S )a   Write a list of data bytes on the channel

           This method can be called to write a list (or any iterable) of
           data bytes to the channel. It is functionality equivalent to
           calling :meth:`write` on each element in the list.

           :param list_of_data:
               The data to send on the channel
           :param datatype: (optional)
               The extended data type of the data, from :ref:`extended
               data types <ExtendedDataTypes>`
           :type list_of_data: iterable of `str` or `bytes`
           :type datatype: `int`

           :raises: :exc:`OSError` if the channel isn't open for sending
                    or the extended data type is not valid for this type
                    of channel

        r   r   )r   r   r   r5  r   r   rW  r[  )r   r\  r   r   s       r   
writelineszSSHChannel.writelines  s\    , >>Xc]L(I JKDhuo|)L MNDzz$))r   c                     | j                   j                  d       | j                  dk(  rd| _        | j                          yy)aP  Write EOF on the channel

           This method sends an end-of-file indication on the
           channel, after which no more data can be sent. The
           channel remains open, though, and data may still be
           sent in the other direction.

           :raises: :exc:`OSError` if the channel isn't open for sending

        zSending EOFr   r   N)r|   r   rg   r   r   s    r   r   zSSHChannel.write_eof  s=     	=)v%,D  " &r   c                 H    | j                   j                  d       d| _        y)a  Pause delivery of incoming data

           This method is used to temporarily suspend delivery of incoming
           channel data. After this call, incoming data will no longer
           be delivered until :meth:`resume_reading` is called. Data will be
           buffered locally up to the configured SSH channel window size,
           but window updates will no longer be sent, eventually causing
           back pressure on the remote system.

           .. note:: Channel close notifications are not suspended by this
                     call. If the remote system closes the channel while
                     delivery is suspended, the channel will be closed even
                     though some buffered data may not have been delivered.

        zReading from channel pausedTN)r|   r   rr   r   s    r   pause_readingzSSHChannel.pause_reading  s    " 	89 r   c                     | j                   r3| j                  j                  d       d| _         | j                          yy)a  Resume delivery of incoming data

           This method can be called to resume delivery of incoming data
           which was suspended by a call to :meth:`pause_reading`. As soon
           as this method is called, any buffered data will be delivered
           immediately. A pending end-of-file notification may also be
           delivered if one was queued while reading was paused.

        zReading from channel resumedFNr   r   s    r   r   zSSHChannel.resume_reading  s9     KK=> %D  "	 r   c                 ,    t        | j                        S )a^  Return the environment for this session

           This method returns the environment set by the client when
           the session was opened. On the server, calls to this method
           should only be made after :meth:`session_started
           <SSHServerSession.session_started>` has been called on the
           :class:`SSHServerSession`. When using the stream-based API,
           calls to this can be made at any time after the handler
           function has started up.

           :returns: A dictionary containing the environment variables
                     set by the client

        )r   rd   r   s    r   get_environmentzSSHChannel.get_environment
  s       		**r   c                     | j                   S )a  Return the command the client requested to execute, if any

           This method returns the command the client requested to
           execute when the session was opened, if any. If the client
           did not request that a command be executed, this method
           will return `None`. On the server, calls to this method
           should only be made after :meth:`session_started
           <SSHServerSession.session_started>` has been called on the
           :class:`SSHServerSession`. When using the stream-based API,
           calls to this can be made at any time after the handler
           function has started up.

        )re   r   s    r   get_commandzSSHChannel.get_command  s     }}r   c                     | j                   S )a  Return the subsystem the client requested to open, if any

           This method returns the subsystem the client requested to
           open when the session was opened, if any. If the client
           did not request that a subsystem be opened, this method will
           return `None`. On the server, calls to this method should
           only be made after :meth:`session_started
           <SSHServerSession.session_started>` has been called on the
           :class:`SSHServerSession`. When using the stream-based API,
           calls to this can be made at any time after the handler
           function has started up.

        )rf   r   s    r   get_subsystemzSSHChannel.get_subsystem-  s     r   )r   rG   )strictNr   NNN)___name__
__module____qualname____doc__r/   globals_handler_namesr   rS   r   int__annotations__rT   rw   AbstractEventLoopr   r   r   propertyr(   r|   r   r   r   r   r   r   r   r   	Exceptionr   r   r   r   r   r   r   rW  rB   r   r   r   r   r   r   r*   r7   r   r   r   r   r5   r	  r  r  r  r  r   r"  r'  r*  r-  r   r   r   r   r   r   r   r   _packet_handlersr3  r   r8  r:  r<  r>  r@  rC  r   rG  rK  rM  rO  r   r[  r   r^  r   ra  r   r   rd  rf  rh  r   r   r   rQ   rQ   U   sa   '%gi@N #OSX%!$c#h&9'_ 9'009'<DSM9'9'&)9'8;9'v 	  
'33 
,eHSM3$67 , $,!Xc] ! !04! & &
$CH $
%SX %
%HY/ %4 %N
(,	#.$#@58I#6 5$ 58@% @8 @ @4/ /( /d /.**)t ) )&HY,? D Pc P P3 P(F);<PAEPZ%7 &
6(::;%0$Z%78%0=A%0N!3 !S !03!=F!KO!,, ,c , , ,s C '059" c  3  ' ,0 (*s *C *'0*59*2S # &+/s C (-1 ) )c )!*)/3)&? ?c ?"+?04?#(, 	"(>!(>(8(9(9	'E '% 'I '*	?3 	?u 	? 	? */5U 55 5"&5375
5 
#(
-5d^
!&!**D *
';3 ; ; ;:%s %t %t "s " =A59%HSM %%-c]%>B%<6& 6H 6 6r )-*x'7 *%*15*:#$!*#"+c!2 +$Xc] "x} r   rQ   c                       e Zd ZU dZded<   ee   ed<   ehZddde	j                  dee   ded	ed
ef fdZdee   dee   dee   deeef   dedee   dededeeef   dee   dee   dededee   fdZdedefdZdedefdZdedefdZdee   fdZdee   fd Zdee   fd!Z	 d.d"ed#ed$ed%edd&f
d'Zd(edd&fd)Zd*eeef   dd&fd+Z d/d,Z!d/d-Z" xZ#S )0SSHClientChannelzSSH client channelrH   r`   rb   rU   rV   rW   rX   rY   rZ   c                 J    t         |   ||||||       d | _        d | _        y rj  )superr   _exit_status_exit_signalr   rU   rV   rW   rX   rY   rZ   	__class__s          r   r   zSSHClientChannel.__init__G  s,     	tXvv{K+/37r   session_factorycommandr   envrequest_pty	term_type	term_size
term_modesx11_forwardingx11_displayx11_auth_pathx11_single_connectionagent_forwardingr   c                 4  K   | j                   j                  d       | j                  d       d{   }|j                           |       | _        | j                  j                  |        || _        || _        || _        |j                         D ]Y  \  }}| j                   j                  d||       | j                  dt        t        |            t        t        |                   [ |r| j                   j                  d|xs d       |s	dx}x}x}}nt        |      d	k(  rBt        t         t"        t"        f   |      \  }}dx}}| j                   j                  d
||       nNt        |      dk(  r5t        t$        |      \  }}}}| j                   j                  d||||       nt'        d      d}|j                         D ]{  \  }}|t(        k  s	|t*        k\  rt'        d|z        t,        j/                  |t        |            }| j                   j1                  d||       |t3        |      t5        |      z   z  }} |t3        t(              z  }| j7                  dt        |xs d      t5        |      t5        |      t5        |      t5        |      t        |             d{   s | j9                          t;        t<        d      |	r| j                   j                  d       	 | j>                  jA                  | |
||       d{   }|r|\  }}}| j7                  dtE        |      t        |      t        tG        jH                  |            t5        |             d{   }|sW| j>                  r| j>                  jK                  |        |	dk7  rt;        tB        d      | j                   j                  d       |r,| j                   j                  d       | j                  d       |r@| j                   j                  d|       | j7                  dt        |             d{   }nv|r@| j                   j                  d|       | j7                  dt        |             d{   }n4| j                   j                  d        | j7                  d!       d{   }|s | j9                          t;        tL        d"      | j                  jO                          | j>                  jQ                  | jS                         | j                          | j                  S 7 7 7 "# t&        $ rG}|	dk7  rt;        tB        t        |            dd}| j                   j                  d       Y d}~kd}~ww xY w7 7 W7 7 w)#zCreate an SSH client sessionzRequesting new SSH sessions   sessionN  Env: %s=%ss   env  Terminal type: %sNoner   r     Terminal size: %sx%srL   %  Terminal size: %sx%s (%sx%s pixels)z8If set, terminal size must be a tuple of 2 or 4 integersr   zInvalid pty mode: %sz  Mode %s: %ds   pty-reqr   zPTY request failed  X11 forwarding enabledignore_failurez'  X11 forwarding attach failure ignoreds   x11-reqzX11 forwarding request failedz(  X11 forwarding request failure ignored  Agent forwarding enableds   auth-agent-req@openssh.com  Command: %ss   exec  Subsystem: %ss	   subsystem  Interactive shell requesteds   shellzSession request failed)*r|   r   r3  r  rb   r  rd   re   rf   itemsr   r8  r3   r   r   r   r   rs  r-   rS  r"   r!   _pty_mode_namesrF  r   r2   r4   r:  r>  r)   r$   r`   attach_x11_listenerr#   r1   binasciib2a_hexr   r%   r   r   r   )r   r  r  r   r  r  r  r  r  r  r  r  r  r  r   r   	env_valuewidthheightpixwidth	pixheightmodesmode
mode_valueattach_resultr   
auth_protoremote_authscreenr   s                                 r   createzSSHClientChannel.createO  s     	56zz*-- 	')%%d+	#"yy{OD)KK~tY?vvc$i'8%c)n57  +
 KK4i6I6J89999IY1$ $U38_i @v'((9""#;UFKY1$59(I5N2vx""#J#(&(IG ! "3 4 4 E$.$4$4$6 j:%)@$%;d%BCC&**4T;""?D*EdfZ&888 %7 T*%%E,,Z-3IO-D-3E]F6N-3H-=-3I->-3E]< < < 

&'>';= = KK9:
P**88k=:OQ Q  2?/
K#11(= >:&x/?/?/L(M6N $ $
 zz

66t<%)99.>;= = ((FH KK;<<=KK_g6--gvgGGFKK.	:--lF9<MNNFKK<=--h77FJJL"#>#;= = 	%%'

t224dkkB}}a .Z<Q P!%55*+M+.s85:>? %)MKK$$%NOOP$. H O 8s   0VT1I>V1T42AV4!T: T7T: AV1V2CV9V:AV;V<4V0V1BV4V7T: :	V
<V?VV

VVVVr   c                     |j                         }|j                          | j                  j                  d|rdnd       | j                  j                  |       y)z/Process a request to set up XON/XOFF processingz)Received XON/XOFF flow control %s requestenabledisableT)r%  r  r|   r   rb   xon_xoff_requested)r   r   client_can_dos      r   _process_xon_xoff_requestz*SSHClientChannel._process_xon_xoff_request  sR     **,D%2		C 	((7r   c                     |j                         dz  }|j                          | j                  j                  d|       || _        | j
                  j                  |       y)z(Process a request to deliver exit status   zReceived exit status %dT)r  r  r|   r   r}  rb   exit_status_received)r   r   statuss      r   _process_exit_status_requestz-SSHClientChannel._process_exit_status_request  sU     ""$t+2F;"**62r   c                 8   |j                         }|j                         }|j                         }|j                         }|j                          	 |j                  d      }|j                  d      }|j                  d      }| j                  j                  d|       | j                  j                  d|       | j                  j                  d|       ||||f| _	        | j                  j                  ||||       y# t        $ r t        d      dw xY w)	z+Process a request to deliver an exit signalr$  utf-8zInvalid exit signal requestNzReceived exit signal %s  Core dumped: %s  Message: %sT)r  r%  r  r   r   r+   r|   r   r   r~  rb   exit_signal_received)	r   r   signal_bytescore_dumped	msg_bytes
lang_bytessignalmsgr  s	            r   _process_exit_signal_requestz-SSHClientChannel._process_exit_signal_request  s    ((*((*%%'	&&(
	I!((1F""7+C$$W-D 	2F;.<?C0#[#t<**6;TJ " 	I =>DH	Is   3D Dc                 N    | j                   | j                   S | j                  ryy)ai  Return the session's exit status

           This method returns the exit status of the session if one has
           been sent. If an exit signal was sent, this method returns -1
           and the exit signal information can be collected by calling
           :meth:`get_exit_signal`. If neither has been sent, this method
           returns `None`.

        N)r}  r~  r   s    r   get_exit_statusz SSHClientChannel.get_exit_status  s+     ($$$r   c                     | j                   S )a  Return the session's exit signal, if one was sent

           This method returns information about the exit signal sent on
           this session. If an exit signal was sent, a tuple is returned
           containing the signal name, a boolean for whether a core dump
           occurred, a message associated with the signal, and the language
           the message was in. Otherwise, this method returns `None`.

        )r~  r   s    r   get_exit_signalz SSHClientChannel.get_exit_signal  s        r   c                     | j                   | j                   S | j                  r$t        j                  | j                  d   d       S y)a  Return the session's exit status or signal

           This method returns the exit status of the session if one has
           been sent. If an exit signal was sent, this method returns
           the negative of the numeric value of that signal, matching
           the behavior of :meth:`asyncio.SubprocessTransport.get_returncode`.
           If neither has been sent, this method returns `None`.

           :returns: `int` or `None`

        Nr   c   )r}  r~  _signal_numbersrF  r   s    r   get_returncodezSSHClientChannel.get_returncode  sI     ($$$#''(9(9!(<bAAAr   r  r  r  r  Nc           	          |s|r | j                   j                  d||||       n| j                   j                  d||       | j                  dt        |      t        |      t        |      t        |             y)a  Change the terminal window size for this session

           This method changes the width and height of the terminal
           associated with this session.

           :param width:
               The width of the terminal in characters
           :param height:
               The height of the terminal in characters
           :param pixwidth: (optional)
               The width of the terminal in pixels
           :param pixheight: (optional)
               The height of the terminal in pixels
           :type width: `int`
           :type height: `int`
           :type pixwidth: `int`
           :type pixheight: `int`

        z0Sending window size change: %sx%s (%sx%s pixels)z!Sending window size change: %sx%ss   window-changeNr|   r   r8  r4   )r   r  r  r  r  s        r   change_terminal_sizez%SSHClientChannel.change_terminal_size0  sn    , yKKO"FHiA KK@%P+VE]F6N!(+VI->	@r   msecc                 r    | j                   j                  d|       | j                  dt        |             y)ay  Send a break to the remote process

           This method requests that the server perform a break
           operation on the remote process or service as described in
           :rfc:`4335`.

           :param msec:
               The duration of the break in milliseconds
           :type msec: `int`

           :raises: :exc:`OSError` if the channel is not open

        zSending %d msec breaks   breakNr  )r   r  s     r   
send_breakzSSHClientChannel.send_breakO  s-     	0$78VD\2r   r  c                     t        |t              r
	 t        |   }| j
                  j                  d|       | j                  dt        |             y# t        $ r t	        dt        |      z        dw xY w)a}  Send a signal to the remote process

           This method can be called to deliver a signal to the remote
           process or service. Signal names should be as described in
           section 6.10 of :rfc:`RFC 4254 <4254#section-6.10>`, or
           can be integer values as defined in the :mod:`signal`
           module, in which case they will be translated to their
           corresponding signal name before being sent.

           .. note:: OpenSSH's SSH server implementation prior to version
                     7.9 does not support this message, so attempts to
                     use :meth:`send_signal`, :meth:`terminate`, or
                     :meth:`kill` with an older OpenSSH SSH server will
                     end up being ignored. This was tracked in OpenSSH
                     `bug 1424`__.

                     __ https://bugzilla.mindrot.org/show_bug.cgi?id=1424

           :param signal:
               The signal to deliver
           :type signal: `str` or `int`

           :raises: | :exc:`OSError` if the channel is not open
                    | :exc:`ValueError` if the signal number is unknown

        zUnknown signal: %sNzSending %s signals   signal)	
isinstancers  _signal_namesKeyErrorrS  r|   r   r8  r3   )r   r  s     r   send_signalzSSHClientChannel.send_signalb  ss    8 fc"O&v. 	,f59fVn5  O !5F!CD$NOs   	A "A5c                 &    | j                  d       y)a  Terminate the remote process

           This method can be called to terminate the remote process or
           service by sending it a `TERM` signal.

           :raises: :exc:`OSError` if the channel is not open

           .. note:: If your server-side runs on OpenSSH,
                     this might be ineffective;
                     for more details, see the note in
                     :meth:`send_signal`

        TERMNr  r   s    r   	terminatezSSHClientChannel.terminate       	 r   c                 &    | j                  d       y)a  Forcibly kill the remote process

           This method can be called to forcibly stop the remote process
           or service by sending it a `KILL` signal.

           :raises: :exc:`OSError` if the channel is not open

           .. note:: If your server-side runs on OpenSSH,
                     this might be ineffective;
                     for more details, see the note in
                     :meth:`send_signal`

        KILLNr  r   s    r   killzSSHClientChannel.kill  r  r   )r   r   rk  )$rm  rn  ro  rp  rt  r8   r   r   rS   rw   ru  r   r   rs  r   r>   r	   r   r.   r,   r   r  r5   r  r  r  r  _ExitSignalr  r  r  r  r  r  r  __classcell__r  s   @r   rz  rz  ?  s     v&&+,O82 8008<DSM88&)88;8|,CF,K |&sm|8@|sCx.|7;| !)| ;F| "+	| =B$)<L	|
 #+3-|
 AI| -1| (,| 1A0H||
	 
d 

9 
 
9  0# $!+!6 ! * BC@# @s @'*@;>@GK@>3s 3t 3&$6%S/ $6d $6L!"!r   rz  c                   r    e Zd ZU dZded<   ee   ed<   ehZddde	j                  deded	ed
ededee   dededef fdZdee   deee   ee   f   fdZdedefdZdedee   fdZdedededdfdZdeddfdZd>dZdedefdZ	 	 d?dee   d ee   defd!Zdedefd"Zdedefd#Zdedefd$Zdedefd%Z dedefd&Z!dedefd'Z"dee   fd(Z#de$fd)Z%d*edee   fd+Z&de'fd,Z(dee   fd-Z)dee   fd.Z*d/eddfd0Z+d1eddfd2Z,d3e-e   ddfd4Z.d5eddfd6Z/d7d8e0fd9ed:ed;ed<eddf
d=Z1 xZ2S )@SSHServerChannelzSSH server channelrI   r`   rb   rU   rV   	allow_ptyline_editor	line_echoline_historymax_line_lengthrW   rX   rY   rZ   c                 F   t         |   ||||	|
|       t        t        t        t        f   |j                  di             | _        || _        || _        || _	        || _
        || _        d| _        d| _        i | _        d| _        | j                   j#                  d       y)z Initialize an SSH server channelenvironmentN)r   r   r   r   zNew SSH session requested)r|  r   r   r	   r   get_key_optionrd   
_allow_pty_line_editor
_line_echo_line_history_max_line_length
_term_type
_term_size_term_modes_x11_displayr|   r   )r   rU   rV   r  r  r  r  r  rW   rX   rY   rZ   r  s               r   r   zSSHServerChannel.__init__  s     	tXvv{Kc3h,,]B?A	 $'#) /)-&&(+/45r   r   r   c                 X   | j                   rt        t        t           |       }t        t        t           |      }t        ||| j                  | j                  | j                        }t        ||      }t        t        t           |      }t        t        t           |      }||fS | }||fS )z0Wrap a line editor around the session if enabled)r  r   r  r   r9   r&   r  r  r  r'   rQ   r   r7   )r   r   server_chanserver_sessioneditor_chaneditor_sessionr  s          r   r   zSSHServerChannel._wrap_session  s     /4d;K!"23"7AN.{N/3/3/A/A/3/D/DFK 2+~NN
6*K8D:f-~>G W} DW}r   r   c                 ^   |j                         }|j                         }|j                         }|j                         }|j                         }|j                         }|j                          | j                  r6| j                  j                  d      r| j                  j                  d      s| j                  j                  d       y	 |j                  d      }||||f}	i }
| j                  j                  d|       |s|r | j                  j                  d||||       n| j                  j                  d	||       d
}|t        |      k  r||   }|dz  }|t        k(  s	|t        k\  rn|dz   t        |      k  rct         j#                  |t%        |            }t&        j)                  |||dz    d      }| j                  j+                  d||       ||
|<   |dz  }nt        d      |t        |      k  r| j,                  j/                  ||	|
      }|rY| j                  j                  d       | j0                  r| j                  j                  d       || _        |	| _        |
| _        |S | j                  j                  d       |S # t        $ r t        d      dw xY w)z+Process a request to open a pseudo-terminalptyz%PTY request denied: PTY not permittedFr$  zInvalid pty requestNr  r  r  r   r   rL   bigz  Mode %s: %szInvalid pty modes stringz  PTY createdz  Line editor enabledz  PTY creation failed)r  r  r  r  r`   check_key_permissioncheck_certificate_permissionr|   r   r   r   r+   r   r   r"   r!   r  rF  r   rs  
from_bytesr   rb   pty_requestedr  r  r  r  )r   r   term_type_bytesr  r  r  r  r  r  r  r  idxr  r   valuer   s                   r   _process_pty_req_requestz)SSHServerChannel._process_pty_req_request  s    !++-!!#""$$$&%%'	!!#zz..u5zz66u=KKDE	A'..w7I FHi8	
0)<yKKF$fh	C KK7GCJ:D1HCz!T_%<1uE
"&**4T;uSQ'7?""?D%@#(
4 q#$>?? CJ ,,Y	:NKK_-    !89'DO'DO)D  KK45Y " 	A 56D@	As   J J,c                    |j                         }|j                         }|j                         }|j                         }|j                          	 t	        j
                  |      }| j                  j                  | j                  |||      | j                         y# t        j                  $ r | j                  j                  d       Y yw xY w)z(Process request to enable X11 forwardingz  Invalid X11 auth dataFN)r%  r  r  r  r  a2b_hexErrorr|   r   r`   r   _finish_x11_req_request)r   r   r   r  	auth_datar  s         r   _process_x11_req_requestz)SSHServerChannel._process_x11_req_request!  s      &&(
%%'	""$	 ((3I
 	

t;;J<Ev O#{{	,  ~~ 	KK89	s   B .CCr  r  r  Nc                 0  K   | j                   j                  | |||       d{   | _        | j                  r-| j                  j	                  d       | j                  d       y| j                  j	                  d       | j                  d       y7 ow)z2Finish processing request to enable X11 forwardingNr  Tz  X11 forwarding failedF)r`   r  r  r|   r   r   )r   r  r  r  s       r   r  z(SSHServerChannel._finish_x11_req_request5  s      #'**"@"@*i#1 1 KK9:!!$'KK89!!%(1s   "BBA0Bc                     |j                          | j                  j                  | j                         | j                         y)z0Process a request to enable ssh-agent forwardingN)r  r`   r   _finish_agent_req_requestr|   r,  s     r   2_process_auth_agent_req_at_openssh_dot_com_requestzCSSHServerChannel._process_auth_agent_req_at_openssh_dot_com_requestC  s1     	

t==?Mr   c                   K   | j                   j                          d{   r-| j                  j                  d       | j	                  d       y| j                  j                  d       | j	                  d       y7 ^w)z4Finish processing request to enable agent forwardingNr  Tz  Agent forwarding failedF)r`   create_agent_listenerr|   r   r   r   s    r   r  z*SSHServerChannel._finish_agent_req_requestK  se      11333KK;<!!$'KK:;!!%( 4s   BA?ABc                 V   |j                         }|j                         }|j                          	 |j                  d      }|j                  d      }| j                  j                  d||       || j                  |<   y# t        $ r | j                  j                  d       Y yw xY w)z0Process a request to set an environment variabler  zInvalid environment dataFr  T)r  r  r   r   r|   r   rd   )r   r   
name_bytesvalue_bytesr   r  s         r   _process_env_requestz%SSHServerChannel._process_env_requestU  s     &&(
'')	$$W-D&&w/E
 	>47		$ " 	KK9:	s   "B $B('B(r  r   c                    t        t        | j                  j                  d            }|)t        t        | j                  j	                  d            }|| j
                  j                  d|       |}|$|| _        | j                  j                  |      }|S |$|| _
        | j                  j                  |      }|S | j                  j                         }|S )z8Tell the session what type of channel is being requestedzforce-commandr  z  Forced command override: %s)r   r   r`   get_certificate_optionr  r|   r   re   rb   exec_requestedrf   subsystem_requestedshell_requested)r   r  r   forced_commandr   s        r   _start_sessionzSSHServerChannel._start_sessiong  s    
 djj77HI 	 !!#tzz'@'@'KLN%KK<nM$G#DM]]11':F  "'DO]]66yAF  ]]224Fr   c                 x    |j                          | j                  j                  d       | j                         S )z!Process a request to open a shellr  )r  r|   r   r  r,  s     r   _process_shell_requestz'SSHServerChannel._process_shell_request  s2     	89""$$r   c                     |j                         }|j                          	 |j                  d      }| j                  j                  d|       | j                  |      S # t        $ r Y yw xY w)z&Process a request to execute a commandr  Fr  )r  r  r  r   r   r|   r   r  )r   r   command_bytesr  s       r   _process_exec_requestz&SSHServerChannel._process_exec_request  sq     ))+	#**73G 	'2""7"33	 " 		   A! !	A-,A-c                     |j                         }|j                          	 |j                  d      }| j                  j                  d|       | j                  |      S # t        $ r Y yw xY w)z%Process a request to open a subsystemr$  Fr  )r   r  )r   r   subsystem_bytesr   s       r   _process_subsystem_requestz+SSHServerChannel._process_subsystem_request  sr     !++-	'..w7I 	*I6""Y"77	 " 		r!  c                 x   |j                         }|j                         }|j                         }|j                         }|j                          |s|r | j                  j                  d||||       n| j                  j                  d||       ||||f| _        | j
                  j                  ||||       y)z+Process a request to change the window sizez,Received window change: %sx%s (%sx%s pixels)zReceived window change: %sx%sT)r  r  r|   r   r  rb   terminal_size_changed)r   r   r  r  r  r  s         r   _process_window_change_requestz/SSHServerChannel._process_window_change_request  s     !!#""$$$&%%'	yKKK"FHiA KK<eVL &(I>++E68YOr   c                     |j                         }|j                          	 |j                  d      }| j                  j                  d|       | j                  j                  |       y# t        $ r Y yw xY w)z"Process a request to send a signalr$  FzReceived %s signalT)r  r  r   r   r|   r   rb   signal_received)r   r   r  r  s       r   _process_signal_requestz(SSHServerChannel._process_signal_request  ss     ((*	!((1F 	-v6%%f- " 		s   A+ +	A76A7c                     |j                         }|j                          | j                  j                  d|       | j                  j                  |      S )z!Process a request to send a breakzReceived %d msec break)r  r  r|   r   rb   break_received)r   r   r  s      r   _process_break_requestz'SSHServerChannel._process_break_request  sH       "148}}++D11r   c                     | j                   S )a  Return the terminal type for this session

           This method returns the terminal type set by the client
           when the session was opened. If the client didn't request
           a pseudo-terminal, this method will return `None`. Calls
           to this method should only be made after :meth:`session_started
           <SSHServerSession.session_started>` has been called on the
           :class:`SSHServerSession`. When using the stream-based API,
           calls to this can be made at any time after the handler
           function has started up.

           :returns: A `str` containing the terminal type or `None` if
                     no pseudo-terminal was requested

        )r  r   s    r   get_terminal_typez"SSHServerChannel.get_terminal_type  s    " r   c                     | j                   S )a  Return terminal size information for this session

           This method returns the latest terminal size information set
           by the client. If the client didn't set any terminal size
           information, all values returned will be zero. Calls to
           this method should only be made after :meth:`session_started
           <SSHServerSession.session_started>` has been called on the
           :class:`SSHServerSession`. When using the stream-based API,
           calls to this can be made at any time after the handler
           function has started up.

           Also see :meth:`terminal_size_changed()
           <SSHServerSession.terminal_size_changed>` or the
           :exc:`TerminalSizeChanged` exception for how to get notified
           when the terminal size changes.

           :returns: A tuple of four `int` values containing the width and
                     height of the terminal in characters and the width
                     and height of the terminal in pixels

        )r  r   s    r   get_terminal_sizez"SSHServerChannel.get_terminal_size  s    . r   r  c                 8    | j                   j                  |      S )a  Return the requested TTY mode for this session

           This method looks up the value of a POSIX terminal mode
           set by the client when the session was opened. If the client
           didn't request a pseudo-terminal or didn't set the requested
           TTY mode opcode, this method will return `None`. Calls to
           this method should only be made after :meth:`session_started
           <SSHServerSession.session_started>` has been called on the
           :class:`SSHServerSession`. When using the stream-based API,
           calls to this can be made at any time after the handler
           function has started up.

           :param mode:
               POSIX terminal mode taken from :ref:`POSIX terminal modes
               <PTYModes>` to look up
           :type mode: `int`

           :returns: An `int` containing the value of the requested
                     POSIX terminal mode or `None` if the requested
                     mode was not set

        )r  rF  r   r  s     r   get_terminal_modez"SSHServerChannel.get_terminal_mode  s    0 ##D))r   c                 ,    t        | j                        S )a  Return the TTY modes for this session

           This method returns a mapping of all the POSIX terminal modes
           set by the client when the session was opened. If the client
           didn't request a pseudo-terminal, this method will return an
           empty mapping. Calls to this method should only be made after
           :meth:`session_started <SSHServerSession.session_started>`
           has been called on the :class:`SSHServerSession`. When using
           the stream-based API, calls to this can be made at any time
           after the handler function has started up.

            :returns: A mapping containing all the POSIX terminal modes
                      set by the client or an empty mapping if no
                      pseudo-terminal was requested

        )r   r  r   s    r   get_terminal_modesz#SSHServerChannel.get_terminal_modes  s    $   0 011r   c                     | j                   S )a  Return the display to use for X11 forwarding

           When X11 forwarding has been requested by the client, this
           method returns the X11 display which should be used to open
           a forwarded connection. If the client did not request X11
           forwarding, this method returns `None`.

           :returns: A `str` containing the X11 display or `None` if
                     X11 forwarding was not requested

        )r  r   s    r   get_x11_displayz SSHServerChannel.get_x11_display,  s        r   c                 6    | j                   j                         S )a  Return the path of the ssh-agent listening socket

           When agent forwarding has been requested by the client,
           this method returns the path of the listening socket which
           should be used to open a forwarded agent connection. If the
           client did not request agent forwarding, this method returns
           `None`.

           :returns: A `str` containing the ssh-agent socket path or
                     `None` if agent forwarding was not requested

        )r`   get_agent_pathr   s    r   r:  zSSHServerChannel.get_agent_path;  s     zz((**r   r  c                 z    | j                   j                  d|rdnd       | j                  dt        |             y)a  Set whether the client should enable XON/XOFF flow control

           This method can be called to tell the client whether or not
           to enable XON/XOFF flow control, indicating that it should
           intercept Control-S and Control-Q coming from its local
           terminal to pause and resume output, respectively.
           Applications should set client_can_do to `True` to
           enable this functionality or to `False` to tell the client
           to forward Control-S and Control-Q through as normal input.

           :param client_can_do:
               Whether or not the client should enable XON/XOFF flow control
           :type client_can_do: `bool`

        z Sending XON/XOFF flow control %sr  r  s   xon-xoffN)r|   r   r8  r1   )r   r  s     r   set_xon_xoffzSSHServerChannel.set_xon_xoffK  s8    " 	;%2		C 	;(>?r   r   c                 0    | j                  |t               y)a0  Write output to stderr

           This method can be called to send output to the client which
           is intended to be displayed on stderr. If an encoding was
           specified when the channel was created, the data should be
           provided as a string and will be converted using that
           encoding. Otherwise, the data should be provided as bytes.

           :param data:
               The data to send to stderr
           :type data: `str` or `bytes`

           :raises: :exc:`OSError` if the channel isn't open for sending

        N)r[  r   )r   r   s     r   write_stderrzSSHServerChannel.write_stderra  s    " 	

4-.r   r\  c                 0    | j                  |t               y)a  Write a list of data bytes to stderr

           This method can be called to write a list (or any iterable) of
           data bytes to the channel. It is functionality equivalent to
           calling :meth:`write_stderr` on each element in the list.

        N)r^  r   )r   r\  s     r   writelines_stderrz"SSHServerChannel.writelines_stderrt  s     	&:;r   r  c                     |dz  }| j                   dvrH| j                  j                  d|       | j                  dt	        |             | j                          yy)a  Send exit status and close the channel

           This method can be called to report an exit status for the
           process back to the client and close the channel. A zero
           exit status is generally returned when the operation was
           successful. After reporting the status, the channel is
           closed.

           :param status:
               The exit status to report to the client
           :type status: `int`

           :raises: :exc:`OSError` if the channel isn't open

        r  >   r]   r   zSending exit status %ds   exit-statusN)rg   r|   r   r8  r4   r>  )r   r  s     r   exitzSSHServerChannel.exit  sS    " 	$#>>KK5v>~vf~>JJL	 ?r   Fr   r  r  r  r  c           	      \   | j                   j                  d|       | j                   j                  d|       | j                   j                  d|       | j                  dvrJ| j	                  dt        |      t        |      t        |      t        |             | j                          yy)a  Send exit signal and close the channel

           This method can be called to report that the process
           terminated abnormslly with a signal. A more detailed
           error message may also provided, along with an indication
           of whether or not the process dumped core. After
           reporting the signal, the channel is closed.

           :param signal:
               The signal which caused the process to exit
           :param core_dumped: (optional)
               Whether or not the process dumped core
           :param msg: (optional)
               Details about what error occurred
           :param lang: (optional)
               The language the error message is in
           :type signal: `str`
           :type core_dumped: `bool`
           :type msg: `str`
           :type lang: `str`

           :raises: :exc:`OSError` if the channel isn't open

        zSending exit signal %sr  r  >   r]   r   s   exit-signalN)r|   r   r   rg   r8  r3   r1   r>  )r   r  r  r  r  s        r   exit_with_signalz!SSHServerChannel.exit_with_signal  s    6 	16:.<?C0#>>~vf~&{3VC[&,PJJL ?r   rk  rl  )3rm  rn  ro  rp  rt  r9   r   r   rT   rw   ru  r   rs  r   r   r   r7   r   rQ   r   r5   r  r	  rW  r  r  r  r  r  r  r   r$  r'  r*  r-  r/  r-   r1  r4  r,   r6  r8  r:  r<  r>  r   r@  rB  r   rD  r  r  s   @r   r  r    s     v&&,-62 6006=A6"6/36CF6 #&6 2:#6 IL6 	6 ,/	60Z%7 *V$j&889*?y ?T ?By Xd^ () )16)@C)HL)N#N(,N)9  $ 7;26hsm "*3-;?4%Y %4 %4I 4$ 48 8t 8Y 4 &i D  2Y 24 28C= &8 2*c *hsm *42I 2(!# !+ + @$ @4 @,/ /D /&	<hv.> 	<4 	<3 4 2 AF$&L"s " "!".1"EI"r   r  c            	       `     e Zd ZdZdeee      ddf fdZdee   de	de	dee   f fd	Z
 xZS )
SSHForwardChannelz:SSH channel for forwarding TCP and UNIX domain connectionsr   r   Nc                    K   t         |   |       d{    | j                  +| j                  j                          | j	                          yy7 <w)z0Finish processing a forward channel open requestN)r|  r   rb   r   r   )r   r   r  s     r   r   z&SSHForwardChannel._finish_open_request  sL      g*6222==$MM))+! % 	3s   AA=Ar  r.  r/  c                 ~  K   t        |   |g|  d{   }|j                           |       | _        | j                  j	                  |        | j                  j                          | j                  J | j                  j                  | j                         | j                         | j                  S 7 w)zOpen a forward channelN)
r|  r3  r  rb   r  r   r`   r   r   r|   )r   r  r.  r/  r   r  s        r   _open_forwardzSSHForwardChannel._open_forward  s     
 w}X555 	')%%d+%%'zz%%%

t224dkkB}} 6s   B=B;B$B=)rm  rn  ro  rp  r*   r7   r   r   r=   rW  rI  r  r  s   @r   rF  rF    sY    D"$Z%78"=A"3DV3L &+49v r   rF  c                       e Zd ZdZdee   dededededede	e   fd	Z
dee   dedededede	e   fd
Zdee   dedededede	e   fdZdededededdf
dZy)SSHTCPChannelzSSH TCP channelr  r.  hostport	orig_host	orig_portr   c                    K   | j                  d||f||f       t        t        t           | j	                  ||t        |      t        |      t        |      t        |             d{         S 7 w)zOpen a TCP channelr   r   peernamelocal_peernameremote_peernameN)rK  r   r:   r   rI  r3   r4   )r   r  r.  rL  rM  rN  rO  s          r   	_open_tcpzSSHTCPChannel._open_tcp  s     
 	W,5y+A-14L 	 	: M&),,_h-3D\6$<-3I->-3I->@ @A 	A@s   A'A4)A2
*	A4c                 J   K   | j                  |d||||       d{   S 7 w)z!Create a new outbound TCP sessions   direct-tcpipNrV  r   r  rL  rM  rN  rO  s         r   connectzSSHTCPChannel.connect  s4     
 nn_o%)4IG G 	H G   #!#c                 J   K   | j                  |d||||       d{   S 7 w)z"Create a new forwarded TCP sessions   forwarded-tcpipNrX  rY  s         r   acceptzSSHTCPChannel.accept  s5     
 nn_6H%)4IG G 	H Gr[  	dest_host	dest_portNc                 4    | j                  d||f||f       y)7Set local and remote peer names for inbound connectionsrQ  rR  NrK  )r   r^  r_  rN  rO  s        r   set_inbound_peer_namesz$SSHTCPChannel.set_inbound_peer_names   s*     	W,5y+A-6	,B 	 	Dr   )rm  rn  ro  rp  r?   r   rW  r   rs  r:   rV  rZ  r]  rc  r   r   r   rK  rK    s   A/CF/K A"'A/2A:=AJMA#&A+8+@AH-A&-I HH&)H69HFIH&!HH,@,H HH&)H69H #H(5f(=HD D D*-D:=DBFDr   rK  c                       e Zd ZdZdee   dedededee   f
dZ	dee   dedee   fdZ
dee   dedee   fd	Zd
eddfdZy)SSHUNIXChannelzSSH UNIX channelr  r.  pathr/  r   c           
         K   | j                  d|       t        t        t            | j                  ||t        |      g|  d{         S 7 w)zOpen a UNIX channelr   rT  rU  N)rK  r   r;   r   rI  r3   )r   r  r.  rf  r/  s        r   
_open_unixzSSHUNIXChannel._open_unix  sb     
 	2tDN6*,$,,_h-3D\B<@B BC 	CBs   AAA
		Ac           	      l   K   | j                  |d|t        d      t        d             d{   S 7 w)z"Create a new outbound UNIX sessions   direct-streamlocal@openssh.comr   r   N)ri  r3   r4   r   r  rf  s      r   rZ  zSSHUNIXChannel.connect  s;      ___%F%)6":vayB B 	B Bs   +424c                 X   K   | j                  |d|t        d             d{   S 7 w)z#Create a new forwarded UNIX sessions!   forwarded-streamlocal@openssh.comr   N)ri  r3   rk  s      r   r]  zSSHUNIXChannel.accept"  s1      ___%I%)6":7 7 	7 7s   !*(*	dest_pathNc                 *    | j                  |d       y)ra  r   rh  Nrb  )r   rm  s     r   rc  z%SSHUNIXChannel.set_inbound_peer_names*  s     	9bIr   )rm  rn  ro  rp  r@   r   rW  r   r;   ri  rZ  r]  rc  r   r   r   re  re  	  s    	C0Ef0M 	C#(	C03	C!&	C+9&+A	C	B-B6-J 	B	B$26$:	B7,A&,I 77#1&#97J J Jr   re  c                        e Zd ZdZdddej
                  dee   dededef fd	Z	dde
dedd
f fdZdde
dedd
f fdZdededee   defdZdedd
fdZ xZS )SSHTunTapChannelzSSH TunTap channelrU   rG   rV   rW   rX   rY   rZ   c                 <    t         |   ||||||       d | _        y rj  )r|  r   _moder  s          r   r   zSSHTunTapChannel.__init__3  s#     	tXvv{K$(
r   Nr   r   r   c                 V    | j                   t        k(  r|dd }t        |   ||       y)z8Strip off address family on incoming packets in TUN moderL   N)rr  rC   r|  r   )r   r   r   r  s      r   r   zSSHTunTapChannel._accept_data:  s,     ::228DT8,r   c                     | j                   t        k(  r'|d   dz	  }|dk(  rt        nt        }t	        |      |z   }t
        |   ||       y)z2Add address family in outbound packets in TUN moder   rL   N)rr  rC   rE   rF   r4   r|  r[  )r   r   r   versionfamilyr  s        r   r[  zSSHTunTapChannel.writeB  sI     ::221glG(/1_:JF&>D(DdH%r   r  r  unitc                    K   || _         |t        }t        t        | j	                  |dt        |      t        |             d{         S 7 w)zOpen a TUN/TAP channelNs   tun@openssh.com)rr  rD   r   r<   rI  r4   )r   r  r  rw  s       r   r   zSSHTunTapChannel.openL  sX      
<#D$,,_-?-3D\6$<I IJ 	JIs   AAA
	Ac                     || _         y)z Set mode for inbound connectionsN)rr  r3  s     r   set_modezSSHTunTapChannel.set_modeZ  s     
r   rj  )rm  rn  ro  rp  rw   ru  r   r   rs  r   rW  rB   r   r[  rA   r<   r   rz  r  r  s   @r   rp  rp  0  s    )_ )00)<DSM))&))8;)- -( -d -&% &8 &t &J*A JJ$,SMJ6FJS T r   rp  c            	       H    e Zd ZdZdee   dededee   fdZ	dededdfdZ
y)	SSHX11ChannelzSSH X11 channelr  rN  rO  r   c                    K   | j                  ||fd       t        t        t           | j	                  |dt        |      t        |             d{         S 7 w)zOpen an SSH X11 channelrQ  rh  s   x11N)rK  r   r:   rW  rI  r3   r4   )r   r  rN  rO  s       r   r   zSSHX11Channel.openc  sl      	Iy+A,3 	 	5 M%(,,_f-3I->-3I->@ @A 	A@s   AAA
	ANc                 .    | j                  d||f       y)z6Set local and remote peer name for inbound connectionsrQ  rh  Nrb  )r   rN  rO  s      r   rc  z$SSHX11Channel.set_inbound_peer_nameso  s"     	7-6	,B 	 	Dr   )rm  rn  ro  rp  r?   rW  r   rs  r:   r   rc  r   r   r   r|  r|  `  sW    
A*>u*E 
A!
A.1
A6CE6J
AD D D Dr   r|  c                   ,    e Zd ZdZdee   dee   fdZy)SSHAgentChannelzSSH agent channelr  r   c                 l   K   t        t        t           | j                  |d       d{         S 7 w)zOpen an SSH agent channels   auth-agent@openssh.comN)r   r;   rW  rI  )r   r  s     r   r   zSSHAgentChannel.openy  s>      N5),,_-FH HI 	IHs   '42
	4N)rm  rn  ro  rp  r@   rW  r;   r   r   r   r   r  r  v  s'    I*?*F I5!Ir   r  )trp  rw   r  r   r   rer  _signaltypesr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   editorr&   r'   loggingr(   miscr)   r*   r+   r,   r-   r.   r/   r0   r   r1   r2   r3   r4   r5   r6   r   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   streamrB   tuntaprC   rD   rE   rF   r\   rG   rH   rI   __dict__rJ   r   rs  rt  r  r  compile_signal_regexvarsr  matchr  r  r   r  r   rQ   rz  r  rF  rK  re  rW  rp  r|  r  )kvs   00r   <module>r     sA  * '     	  " B B C C * *  9 B B N N ? G G 9 K >  = = 2 2 4 N N C C D D ? @ ,  ? 5 >/ "+!3!3WS#X 3";:#K1A2F 

:&/3G}/B/B/D ./DVa#))!, QR5#a&=/D .$3$9$9$;<$;&1aA$;<CsC'(8YK$$?@Ag"2 gTi!z76? i!XOz76? Od
GFO B(D%wv (DV$J& $JN-(/ -`D%e, D,	I'. 	ISA.<s   3'I1I$