
    mgΕ                        d Z ddlZddlZddl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mZmZmZ ddlmZ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# ddlm$Z$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/ ddl&m0Z0m1Z1m2Z2 ddl&m3Z3m4Z4 erddl5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ede<e=e"df   Z>ee<e!f   Z?eee>e?f   e>e?f   Z@ G d de      ZAdddefdeeB   de dee<   deCdeCde=deBfd ZDd!e<deeEeEe<f   fd"ZFd!e<deeEeEf   fd#ZGde@deed   e?eCf   fd$ZHd%dd&eCd'eCd(eCd)eCde?ded*   fd+ZI G d, d-ej                        ZK G d. d/ej                        ZM G d0 d1      ZN G d2 d3eN      ZO G d4 d5eN      ZP G d6 d7      ZQ	 dGdde3ddd8d9ee@ee@   f   d:e@d(eCd)eCd;eEd<e2d=e1ddfd>ZRd?e*d@e=dAdBdCdDdEdDde#d   fdFZSy)HzSCP handlers    N)PurePath)TracebackType)TYPE_CHECKINGAsyncIteratorListNoReturnOptional)SequenceTupleTypeUnioncast)ProtocolSelf   )DEFAULT_LANG)FILEXFER_TYPE_REGULARFILEXFER_TYPE_DIRECTORY)	SSHLogger)
BytesOrStrFilePathHostPort
MaybeAwait)async_context_managerplural)	SFTPAttrsSFTPGlobSFTPName
SFTPServerSFTPServerFS)SFTPFileProtocol	SFTPErrorSFTPFailureSFTPBadMessage)SFTPConnectionLostSFTPErrorHandlerSFTPProgressHandler)SFTP_BLOCK_SIZElocal_fs)SSHServerChannel)SSHClientConnection)	SSHReader	SSHWriterr+   c                       e Zd ZdZededefd       ZdeddfdZdeddddfd	Zdede	fd
Z
dede	fdZdedee   fdZdeddfdZedededefd       Zy)_SCPFSProtocolz6Protocol for accessing a filesystem during an SCP copypathreturnc                      y)z0Return the final component of a POSIX-style pathN )r0   s    ,lib/python3.12/site-packages/asyncssh/scp.pybasenamez_SCPFSProtocol.basename?           r   c                    K   yw)z9Get attributes of a file or directory, following symlinksNr3   selfr0   s     r4   statz_SCPFSProtocol.statC           attrsNc                    K   yw)z%Set attributes of a file or directoryNr3   )r:   r0   r>   s      r4   setstatz_SCPFSProtocol.setstatF   r<   r=   c                    K   yw)zReturn if a path existsNr3   r9   s     r4   existsz_SCPFSProtocol.existsI   r<   r=   c                    K   yw)z(Return if the path refers to a directoryNr3   r9   s     r4   isdirz_SCPFSProtocol.isdirL   r<   r=   c                      y)z5Read the names and attributes of files in a directoryNr3   r9   s     r4   scandirz_SCPFSProtocol.scandirO   r6   r7   c                    K   yw)zCreate a directoryNr3   r9   s     r4   mkdirz_SCPFSProtocol.mkdirR   r<   r=   modec                    K   yw)zOpen a fileNr3   )r:   r0   rI   s      r4   openz_SCPFSProtocol.openU   r<   r=   )__name__
__module____qualname____doc__staticmethodbytesr5   r;   r@   boolrB   rD   r   r   rF   rH   r   strr!   rK   r3   r7   r4   r/   r/   <   s    @?u ? ? ?Hu H H4% 4 4 4& &4 &7 7$ 7DE DmH&= D! !$ ! u C 4D  r7   r/   F	exc_classreasonr0   fatalsuppress_sendlangr1   c                     t        |t              r|j                  dd      }|r|dz   |j                  dd      z   } | ||      }t        |d|       t        |d|       |S )z,Construct SCP version of SFTPError exceptionutf-8replace)errorsz: rV   rW   )
isinstancerQ   decodesetattr)rT   rU   r0   rV   rW   rX   excs          r4   
_scp_errorra   Z   sg     &% wy9$WY!GG
FD
!CC% C-0Jr7   argsc                     	 | j                  dd      \  }}}t        |d      t        |      |fS # t        $ r t        t        d      dw xY w)z-Parse arguments to an SCP copy or dir requestN      zInvalid copy or dir requestsplitint
ValueErrorra   r$   )rb   permissionssizenames       r4   _parse_cd_argsrm   n   s^    B"&**T1"5T4;"CIt33 B68=A	BBs	   -0 Ac                     	 | j                         \  }}}}t        |      t        |      fS # t        $ r t        t        d      dw xY w)z%Parse argument to an SCP time requestzInvalid time requestNrf   )rb   mtime_atimes       r4   _parse_t_argsrr   y   sP    K!ZZ\q%5z3u:%% K)?@dJKs	   *- Ac                   K   ddl m} t        | t              r!t	        t
        t        t        f   |       \  }} nt        | t              r3t        j                  dk(  r | dd t        j                  v r| dd dk(  rd}nt        | t              rd| v r| j                  dd      \  }} n]t        | t              r+d| v r'| j                  dd      \  }} |j                  d      }n"t        | t        t        t         f      rd}n| }d	} t        |t              rd
} ||fi | d{   }n%t        |t              rd
} ||i | d{   }nd}t	        t"        d   |      t	        t        |       |fS 7 N7 -w)z8Convert an SCP path into an SSHClientConnection and pathr   )connectwin32Nrd   :   :rZ      .TFr+   ) rt   r]   tupler   r   _SCPConn_SCPPathrS   sysplatformstringascii_lettersrg   rQ   r^   r   r	   )r0   kwargsrt   conn
close_conns        r4   _parse_pathr      s[    
  $%( 23T:
d	D#	3<<7#:!H,,,1I	D#	3$;ZZQ'
d	D%	 TT\ZZa(
d{{7#	D5#x0	1$
T,V,,	D%	 
d-f--
/0$74 *. . - .s$   D E5"E1#"E5E3,E53E5r   sourcemust_be_dirpreserverecurse)SSHReader[bytes]SSHWriter[bytes]c                 j  K   t        |t              rt        |      }t        |t              r|j                  d      }d|rdndz   |rdndz   |rdndz   |rdndz   |z   }| j                  j                  d	      j                  d
|dd        | j                  |d       d{   \  }}}	||fS 7 w)zStart remote SCP serverrZ   s   scp s   -f s   -t s   -d r7   s   -p s   -r sftpzStarting remote SCP, args: %s   N)encoding)r]   r   rS   encodelogger	get_childinfoopen_session)
r   r   r   r   r   r0   commandwriterreaderrp   s
             r4   _start_remoter      s      $!4y${{7#F&7%30"- "s, /33G
 	KK&!&&'F'.qr{4 #//$/GGFFA6> Hs   B"B3$B1%B3c                   D    e Zd ZU dZeed<   eed<   eed<   eed<   eed<   y)_SCPArgszSCP command line argumentsr0   r   r   r   r   N)rL   rM   rN   rO   rS   __annotations__rR   r3   r7   r4   r   r      s    $
ILNMr7   r   c                   D     e Zd ZdZd fdZdedefdZdedefdZ	 xZ
S )	_SCPArgParserzA parser for SCP argumentsr1   c                 \   t         |   d       | j                  d      }|j                  ddd       |j                  d	dd
       | j                  ddd       | j                  ddd       | j                  ddd       | j                  ddd       | j                  d       y )NF)add_helpT)requiredz-fr   
store_true)destactionz-tstore_falsez-dr   z-pr   z-rr   z-vverboser0   )super__init__add_mutually_exclusive_groupadd_argument)r:   group	__class__s     r4   r   z_SCPArgParser.__init__   s    %(1141@4h|D4h}E$]<H$ZE$Y|D$Y|D&!r7   messagec                     t        |      N)ri   )r:   r   s     r4   errorz_SCPArgParser.error   s    !!r7   r   c                 d    | j                  t        j                  |      dd t                     S )zParse an SCP commandr   N)	namespace)
parse_argsshlexrg   r   )r:   r   s     r4   parsez_SCPArgParser.parse   s)     u{{73AB78:NNr7   r1   N)rL   rM   rN   rO   r   rS   r   r   r   r   __classcell__r   s   @r4   r   r      s4    $""S "X "OS OX Or7   r   c            	       ,   e Zd ZdZ	 d dddddedefd	Zd
efdZde	e
e      de	e   de	e   d
efdZed
efd       Zd
e	e   fdZded
dfdZded
dfdZded
dfdZd!dZded
dfdZd
ee	e   e	e   f   fdZded
efdZded
dfdZd"ded
dfdZy)#_SCPHandlerzSCP handlerNr   r   r   r   error_handlerserverc                 |    || _         || _        || _        || _        |j                  j                  d      | _        y )Nr   )_reader_writer_error_handler_serverr   r   _logger)r:   r   r   r   r   s        r4   r   z_SCPHandler.__init__   s5    +}}..v6r7   r1   c                    K   | S w)z8Allow _SCPHandler to be used as an async context managerr3   r:   s    r4   
__aenter__z_SCPHandler.__aenter__   s      s   	_exc_type
_exc_value
_tracebackc                 @   K   | j                          d{    y7 w)z9Wait for file close when used as an async context managerNF)close)r:   r   r   r   s       r4   	__aexit__z_SCPHandler.__aexit__   s      jjl 	s   c                     | j                   S z)A logger associated with this SCP handlerr   r   s    r4   r   z_SCPHandler.logger       ||r7   c                 n  K   | j                   j                  d       d{   }|dk7  rj| j                   j                          d{   }|r|j                  d      st	        t
        ddd      |dvr||z   }t	        t        |dd	 |d
k7  d      S | j                  j                  d       y7 7 jw)zWait for an SCP responser   N       
Connection lostTrV   rW         zReceived SCP OK)	r   readreadlineendswithra   r%   r#   r   debug1)r:   resultrU   s      r4   await_responsez_SCPHandler.await_response  s      ||((++U?<<0022F!7 !35F'+4A A [(&k6#2;$*g$5TK K 	,-# , 3s"   B5B1&B5B3	A)B53B5rb   c                     dj                  |      }| j                  j                  d|       | j                  j	                  |dz          y)zSend an SCP requestr7   zSending SCP request: %sr   N)joinr   r   r   write)r:   rb   requests      r4   send_requestz_SCPHandler.send_request  s<     ((4.4g>7U?+r7   c                 f   K    | j                   |  | j                          d{   }|r|y7 	w)z+Send an SCP request and wait for a responseN)r   r   )r:   rb   r`   s      r4   make_requestz_SCPHandler.make_request&  s;      	4 ''))I  *s   #1/
1datac                 &  K   | j                   j                  dt        t        |      d             | j                  j                  |       | j                  j                          d{    t        j                  d       d{    y7 "7 w)zSend SCP file dataz
Sending %sSCP data byteNr   )	r   r   r   lenr   r   drainasynciosleep)r:   r   s     r4   	send_dataz_SCPHandler.send_data0  sj      	<D	?)KL4 ll  """mmA 	#s$   A(B*B+BBBBc                 p    | j                   j                  d       | j                  j                  d       y)zSend an SCP OK responsezSending SCP OKr   N)r   r   r   r   r   s    r4   send_okz_SCPHandler.send_ok9  s)     	+,5!r7   r`   c                 :   t        |t              r|j                  j                  d      }nt        |t              ra|j
                  j                  d      }t        t        |j                        }|rDt        |t              r|j                  d      }|d|z   z  }nt        |      j                  d      }t        t        t        |dd            }| j                  j                  d|rdnd|       | j                  j                  |rdnd	d
z   |z   dz          y)zSend an SCP error responserZ   s   : rV   FzSending SCP %serror: %sfatal ry      r      scp: r   N)r]   r"   rU   r   OSErrorstrerrorr   r   filenamerS   rR   getattrr   r   r   r   )r:   r`   rU   r   rV   s        r4   
send_errorz_SCPHandler.send_error@  s     c9%ZZ&&w/FW%\\((1FJ5Hh,'w7H%(**X__W-FT73784',8"f	> 	uG'#$&,-/45 	6r7   c                   K   | j                   j                          d{   }|sy|dd |dd }}|dvr!| j                  j                  d||       ||fS | j                  j                  d|dk7  rd	nd
|       ||fS 7 ^w)zReceive SCP requestN)NNr   r   r   zReceived SCP request: %s%szReceived SCP %serror: %sr   r   ry   )r   r   r   r   )r:   r   r   rb   s       r4   recv_requestz_SCPHandler.recv_requestZ  s      --//r{GAbM$KK;VTJ
 t| KK9+1W+<x2tM t| 0s   BA?ABnc                    K   | j                   j                  |       d{   }| j                  j                  dt	        t        |      d             |S 7 5w)zReceive SCP file dataNzReceived %sr   )r   r   r   r   r   r   )r:   r   r   s      r4   	recv_dataz_SCPHandler.recv_datam  sH      \\&&q))=&TO*LM	 *s   AA6Ac                 D   t        |t              rt        t        ddd      }t	        |dd      s| j                  |       | j                  j                  dt        |             t	        |dd      s| j                  |d| j                  r| j                  |       yy)	Handle an SCP errorr   Tr   rW   FHandling SCP error: %srV   N)
r]   BrokenPipeErrorra   r%   r   r   r   r   rS   r   r:   r`   s     r4   handle_errorz_SCPHandler.handle_errorv  s     c?+/1B#'t=C sOU3OOC 3SX>3'4+>+>+F4  $ !r7   	cancelledc                   K   | j                   j                  d       |r%| j                  j                  j	                          nV| j
                  r0t        d| j                  j                        j                  d       n| j                  j                          | j                  j                  j                          d{    y7 w)zClose an SCP sessionzStopping remote SCPr*   r   N)
r   r   r   channelabortr   r   exitr   wait_closed)r:   r  s     r4   r   z_SCPHandler.close  s      	./LL  &&(\\#T\\%9%9:??BLL ll""..000s   C C
CC
)NFr   )F)rL   rM   rN   rO   r&   rR   r   r   r   r	   r   BaseExceptionr   r   propertyr   r   	Exceptionr   rQ   r   r   r   r   r   r   r   rh   r   r   r   r3   r7   r4   r   r      sK    IN71 7;M 7 07AE7$ 
$}2E)F $,]$;$,]$;  	  
hy&9 ,,% ,D , $ E d "6i 6D 64E(5/8E?*J$K &  %	 %d %"1T 1d 1r7   r   c                        e Zd ZdZedddfdeddddd	ed
ededede	def fdZ
dededededdf
dZdeddfdZdedededdfdZdedededdfdZdedededdfdZdeddfdZ xZS )
_SCPSourcezSCP handler for sending filesNFfsr   r   r   r   r   r   
block_sizeprogress_handlerr   r   c
                 p    t         
|   ||||	       || _        || _        || _        || _        || _        y r   )r   r   _fs	_preserve_recurse_block_size_progress_handler)r:   r  r   r   r   r   r  r  r   r   r   s             r4   r   z_SCPSource.__init__  s=    
 	?!%!1r7   r   r>   rk   r0   r1   c                    K   |j                   J d|j                   dz  |fz  }| j                  ||j                  d      | j                  j	                  |             d{    y7 w)zMake an SCP copy or dir requestNz%04o %d i  ascii)rj   r   r   r  r5   )r:   r   r>   rk   r0   rb   s         r4   _make_cd_requestz_SCPSource._make_cd_request  sk        ,,,U..7>>G(< $ 1 1$ 79 	9 	9s   A!A+#A)$A+c                 F  K   | j                   j                  dt        |j                  |j                               |j                  J |j                  J d|j                  |j                  fz  }| j                  d|j                  d             d{    y7 w)zMake an SCP time request    Preserving attrs: %s)rq   ro   Nz	%d 0 %d 0   Tr  )r   r   r   rq   ro   r   r   )r:   r>   rb   s      r4   _make_t_requestz_SCPSource._make_t_request  s      	3"EKKH	J {{&&&{{&&&ekk5;;77dkk'&:;;;s   BB!BB!srcpathdstpathc                   K   |j                   J | j                  j                  |d       d{   }|j                   }d}d}| j                  j	                  d||       	 | j                  d|||       d{    | j                  r|dk(  r| j                  ||dd       ||k  rt        ||z
  | j                        }|r|dz  }	n<	 t        t        |j                  ||       d{         }	|	st        t        d      	 | j!                  	       d{    |t#        |	      z  }| j                  r| j                  ||||       ||k  r|j%                          d{    |r| j'                  |       t)        |dd	       n| j+                          | j-                          d{   }|xs |}|r|y7 7 H7 # t        t        f$ r}
|
}Y d}
~
d}
~
ww xY w7 7 # |j%                          d{  7   w xY w7 Ww)
zSend a file over SCPNrbr   z  Sending file %s, size %d   Cr   zUnexpected EOFrW   T)rk   r  rK   r   r   r  r  minr  r   rQ   r   ra   r#   r   r"   r   r   r   r   r_   r   r   )r:   r  r  r>   file_objrk   	local_excoffsetblocklenr   r`   
remote_exc	final_excs                r4   
_send_filez_SCPSource._send_file  s     zz%%%w55zz	5wE	#''eT7CCC%%$!)&&wA>4-tf}d.>.>?#e+D(#E*2--&*I$I K  $",[:J"KK  $
 nnT***#d)#))**7GVTJ' 4-* .."""OOI&I5LLN..00
+)	O [ 6 D %J $Y/ ($'	( + #(..""" 1s   .H	F?1H	#G) :G;AG) G *G
+G G) G%7G) H	&G''AH	/H0H	G) G G"GG) G""G) 'H	)H=H >HH	c                   K   | j                   j                  d|       | j                  d|d|       d{    | j                  j	                  |      2 3 d{   }t        t        |j                        }|dv r(| j                  t        j                  ||      t        j                  ||      |j                         d{    v7 7 s7 	6 | j                  d       d{  7   | j                   j                  d|       yw)zSend directory over SCPz  Starting send of directory %s   Dr   N)rx   s   ..   Ez  Finished send of directory %s)r   r   r  r  rF   r   rQ   r   _send_files	posixpathr   r>   r   )r:   r  r  r>   entryrl   s         r4   	_send_dirz_SCPSource._send_dir  s      	:GD##D%G<<<88++G4 	0%u~~.D}$""9>>'4#@#,>>'4#@#(;;0 0 0 	=	00 5 %%%:GDsR   4D
CD
CCCA(D
CD
CD
D
'C*("D
c                   K   	 | j                   r| j                  |       d{    | j                  r/|j                  t        k(  r| j                  |||       d{    y|j                  t        k(  r| j                  |||       d{    yt        t        d|      7 7 G7 # t        t        t        f$ r}| j                  |       Y d}~yd}~ww xY ww)zSend files via SCPNzNot a regular file)r  r  r  typer   r/  r   r(  ra   r#   r   r"   ri   r   )r:   r  r  r>   r`   s        r4   r,  z_SCPSource._send_files  s     	#~~**5111}}/F!FnnWgu===44oogw>>> .BGLL 2 >> J/ 	#c""	#sn   C B* B$9B* B&B* #C$)B* B(B* CB* &B* (B* *C>CCCCc                   K   d}	 t        |t              rt        |      }t        |t              r|j                  d      }| j	                          d{   }|r|t        | j                        j                  |       d{   D ]?  }| j                  t        t        |j                        d|j                         d{    A 	 | j%                  |       d{    y7 7 c7 %# t        j                  $ r d}Y 7t        t         f$ r}| j#                  |       Y d}~[d}~ww xY w7 N# | j%                  |       d{  7   w xY ww)zStart SCP transferFrZ   Nr7   T)r]   r   rS   r   r   r   r  matchr,  r   rQ   r   r>   r   CancelledErrorr   r"   r   r   )r:   r  r  r`   rl   s        r4   runz_SCPSource.run  s     		('8,g,'3'!..1++--C	&txx066w???&&tE4=='A,/= = = @ **Y''' .
 @=%% 	I# 	#c""	# ($**Y'''s   EAC- C'/C- C)?C- C+C- D2 E!D0"E'C- )C- +C- -D-D2 D-D(#D2 (D--D2 0E2EE
EE)rL   rM   rN   rO   r(   r/   rR   rh   r'   r&   r   rQ   r   r  r  r(  r/  r,  r|   r5  r   r   s   @r4   r  r    s(   ' $39=37	2> 23E 2+27;2FJ2 2 $72 !1	2 BF	29U 99 9%(9059:>9
<9 
< 
<4 4"'4094>B4lEu Eu E(E-1E,# # #!*#/3#"( (d (r7   r  c                        e Zd ZdZedddfdeddddd	ed
edededede	def fdZ
dedededdfdZdededdfdZdededdfdZdeddfdZ xZS )_SCPSinkzSCP handler for receiving filesNFr  r   r   r   r   r   r   r   r  r  r   r   c                 ~    t         |   |||	|
       || _        || _        || _        || _        || _        || _        y r   )r   r   r  _must_be_dirr  r  r  r  )r:   r  r   r   r   r   r   r  r  r   r   r   s              r4   r   z_SCPSink.__init__8  sE    
 	?'!%!1r7   r  r  rk   r1   c                   K   | j                   j                  |d       d{   }d}d}| j                  j                  d||       	 | j	                          | j
                  r|dk(  r| j                  ||dd       ||k  rt        ||z
  | j                        }| j                  |       d{   }|st        t        ddd      |s	 |j                  ||       d{    |t        |      z  }| j
                  r| j                  ||||       ||k  r|j                          d{    | j!                          d{   }
|r| j#                  |       t%        |dd       n| j	                          |
xs |}|r|y7 e7 7 # t        t        f$ r}	|	}Y d}	~	d}	~	ww xY w7 }# |j                          d{  7   w xY w7 w)	zReceive a file via SCPwbNr   z  Receiving file %s, size %dr   Tr   rW   )r  rK   r   r   r   r  r!  r  r   ra   r%   r   r   r"   r   r   r   r   r_   )r:   r  r  rk   r"  r#  r$  r%  r   r`   r&  r'  s               r4   
_recv_filez_SCPSink._recv_fileF  s     w55	7$G	#LLN%%$!)&&wA>4-tf}d.>.>?!^^H55$%79J+/tE E !(&nnT6::: #d)#))**7GVTJ# 4-& .."""..00
OOI&It4LLN+)	O W 6 6 ;#Y/ ($'	( #(.."""0s    GF%G	A'F. 0F
1F. F "F#F '3F. G.F,/GGAG
F. F F)F$F. $F))F. ,G.G	GG		Gc                   K   | j                   st        t        d      | j                  j	                  d|       | j
                  j                  |       d{   r4| j
                  j                  |       d{   s4t        t        d|      | j
                  j                  |       d{    | j                  ||       d{    | j                  j	                  d|       y7 7 q7 ?7 'w)zReceive a directory over SCPz"Directory received without recursez"  Starting receive of directory %sNNot a directoryz"  Finished receive of directory %s)r  ra   r$   r   r   r  rB   rD   r#   rH   _recv_files)r:   r  r  s      r4   	_recv_dirz_SCPSink._recv_dirx  s      }}^AC C 	=wG)))000 .?II((..)))w000=wG *0 *0sH   AC4C,"C4<C.=3C40C01C4
C2"C4.C40C42C4c                   K   | j                          t               }	 | j                          d{   \  }}|sy|J 	 |dv rt        t        ||dk7  d      |dk(  r6| j
                  rt        |      \  |_        |_        | j                          n#|dk(  r| j                          y|dv r	 t        |      \  |_
        }}t        j                  ||      }| j                  j                  |       d{   rt        j                  ||      }	n|}	|d	k(  r| j                  ||	       d{    n| j!                  ||	|       d{    | j
                  r@| j"                  j%                  d
|       | j                  j'                  |	|       d{    t               }nt        t(        d      7 7 7 7 t7 *# t               }w xY w# t*        t,        f$ r}
| j/                  |
       Y d}
~
Ad}
~
ww xY ww)zReceive files over SCPTNr   r   r   r  r+     CDr*  r  zUnknown request)r   r   r   ra   r#   r  rr   rq   ro   rm   rj   r-  r   r  rD   r@  r<  r   r   r@   r$   r   r"   r   )r:   r  r  r>   r   rb   rk   rl   new_srcpathnew_dstpathr`   s              r4   r?  z_SCPSink._recv_files  s     	!%!2!2!44LFD###%'[($[$f>O379 9t^~~3@3F0U[LLNt^LLNu_,8Ft8L5)4&/nnWd&C!%!888*3..$*GK*1K!T>"&..k"JJJ"&//+2=t#E E E  >> KK,,-GO"&(("2"2;"FFF )$^5FGGW 42 9 KE
 G ) Y' '!!#&&'s   /HF;HA*G +H,G 1AG 9F>:7G 1G 2G GAG GG G 9H>G  G G G GG G?$G:5H:G??Hc                 x  K   d}	 t        |t              rt        |      }t        |t              r|j                  d      }| j                  rD| j
                  j                  |       d{   s!| j                  t        t        d|             n| j                  d|       d{    | j!                  |       d{    y7 Y7  # t        j                  $ r}d}Y d}~8d}~wt        t        t        f$ r}| j                  |       Y d}~ed}~ww xY w7 X# | j!                  |       d{  7   w xY ww)zStart SCP file receiveFrZ   Nr>  r7   T)r]   r   rS   r   r9  r  rD   r   ra   r#   r?  r   r4  r   r"   ri   r   )r:   r  r  r`   s       r4   r5  z_SCPSink.run  s     		('8,g,'3'!..1  txx~~g/F)F)F!!*[:K-4#6 7 &&sG444 **Y''' *G 5%% 	IJ/ 	#c""	# ($**Y'''s   D:A&C
 ,C-:C
 'C(C
 ,D: DD:C
 C
 
DC$D $D;DD DD D:D70D31D77D:)rL   rM   rN   rO   r(   r/   rR   rh   r'   r&   r   rQ   r<  r@  r?  r|   r5  r   r   s   @r4   r7  r7  5  s    ) 3B9=37	2> 23E 2+2:>2JN22,/2 $72 !1	2 BF	20 0"'0/207;0dHu Hu H H&4' 4' 4'4 4'l( (d (r7   r7  c                       e Zd ZdZeddfddddddddd	ed
edefdZe	de
fd       ZdeddfdZdededee   fdZdededdfdZddZddZy)
_SCPCopierz'SCP handler for remote-to-remote copiesN
src_readerr   
src_writerr   
dst_reader
dst_writerr  r  r   c                     t        ||      | _        t        ||      | _        | j                  j                  | _        || _        || _        || _        y r   )r   _source_sinkr   r   r  r  r   )r:   rH  rI  rJ  rK  r  r  r   s           r4   r   z_SCPCopier.__init__  sI     #:z: Z8
||**%!1+r7   r1   c                     | j                   S r   r   r   s    r4   r   z_SCPCopier.logger  r   r7   r`   c                     t        |t              rt        t        dd      }| j                  j                  dt        |             | j                  rt        |dd      s| j                  |       y|)r   r   TrV   r   rV   FN)	r]   r   ra   r%   r   r   rS   r   r   r   s     r4   _handle_errorz_SCPCopier._handle_error  s^     c?+/1B$OC3SX>wsGU'C$Ir7   srcdstc                    K   	 |j                          d{   }|r|j                  |       |S |j                          y7 *# t        $ r}|cY d}~S d}~ww xY ww)z6Forward an SCP response between two remote SCP serversN)r   r   r   r   )r:   rS  rT  r`   s       r4   _forward_responsez_SCPCopier._forward_response  sW     
	**,,Cs#
 -  	J	sN   AA AA AA AA 	AAAAAAr0   rk   c                   K   | j                   j                  d||       d}| j                  r|dk(  r| j                  ||dd       ||k  rt        ||z
  | j                        }| j
                  j                  |       d{   }|st        t        dd      | j                  j                  |       d{    |t        |      z  }| j                  r| j                  ||||       ||k  r| j                  | j
                  | j                         d{   }| j                  | j                  | j
                         d{   }|xs |}|r| j                  |       yy7 7 7 Q7 %w)z1Copy a file from one remote SCP server to anotherz  Copying file %s, size %dr   Nr   TrQ  )r   r   r  r!  r  rM  r   ra   r%   rN  r   r   rV  rR  )	r:   r0   rk   r$  r%  r   
source_excsink_excr`   s	            r4   
_copy_filez_SCPCopier._copy_file  sT     	5tTB!!dai""4q!4tm4&=$*:*:;H//99D !35F'+- - **&&t,,,c$iF%%&&tT64@ tm  11$,,

KK
//

DLLII$*s# # : - LIsN   BE2E*6E2:E,;7E23)E2E.-E2
E0 E2,E2.E20E2c                   K   | j                  | j                  | j                         d{   }|r| j                  |       g }g }t	               }	 | j                  j                          d{   \  }}|sy|J | j                  j                  ||       |dv r't        t        ||dk7        }| j                  |       t| j                  | j                  | j                         d{   }|r| j                  |       |dv r	 t        |      \  |_
        }}|dk(  rLdj                  ||gz         }	| j                  |	|       d{    | j                  j                  d|       nM|j                  |       |j                  |       | j                  j                  d	dj                  |             t	               }n|d
k(  rk|rh| j                  j                  ddj                  |             |j!                          |j!                         }| j                  j                  d|       n/y|dk(  rt#        |      \  |_        |_        nt        t(        d      7 >7 7 7 ## t	               }w xY ww)z)Copy files from one SCP server to anotherNr   r   rQ  rB  r      /r  z  Starting copy of directory %sr+  z  Finished copy of directory %sr  zUnknown SCP action)rV  rN  rM  rR  r   r   r   ra   r#   rm   rj   r   rZ  r   r   appendpoprr   rq   ro   r$   )
r:   r`   pathlistattrlistr>   r   rb   rk   rl   r0   s
             r4   _copy_filesz_SCPCopier._copy_files0  s7     **4::t||DDs# "$&!%!:!:!<<LFD###JJ##FD1$ d&G:KL""3'..tzz4<<HHC""3'(4B44H1E%tT~#yyTF):;"oodD999(()CUK - .(()J)-8)<> &KE4KK$$%F%)YYx%8: LLN$LLNEKK$$%?G4+8+>(U[ 1EFFe  E = I : &KEsb   *JI*AJ0I-1A>J/I00JAI6 I3A.I6 ?B,J-J0J3I6 6JJc                   K   d}	 | j                          d{    | j                  j                  |       d{    | j                  j                  |       d{    y7 K# t        j                  $ r d}Y `t        t        f$ r}| j                  |       Y d}~d}~ww xY w7 m7 L# | j                  j                  |       d{  7   | j                  j                  |       d{  7   w xY ww)z#Start SCP remote-to-remote transferFNT)	ra  r   r4  r   r"   rR  rM  r   rN  )r:   r  r`   s      r4   r5  z_SCPCopier.runp  s      		.""$$$ ,,$$Y///**""9--- %%% 	I# 	$s##	$ 0- ,,$$Y///**""9---s   C;A' A%A' C;B*"C;B, C;%A' 'B'<B. >B'B"B. "B''B. *C;,C;.C8C#C81C42C88C;r   )rL   rM   rN   rO   r(   rh   r'   r&   r   r  r   r   r	  rR  r   r	   rV  rQ   rZ  ra  r5  r3   r7   r4   rG  rG    s    1 $39=37,#5 ,/,/, 0, !	,
 $7, !1, 	  
 t ; %05=i5H$$U $# $$ $@>G@.r7   rG  )r   r   r  r  r   srcpathsr  r  r  r   c                  K   t        | t        t        t        f      st        | t              rt        |       dk(  r| g} t        |       dkD  }t        |fi | d{   \  }	}}
	 | D ]V  }t        |fi | d{   \  }}}	 |rb|	r`t        |d||||       d{   \  }}t        |	d||||       d{   \  }}t        |||||||      }|j                          d{    n|rLt        |d||||       d{   \  }}t        t        ||||||||	      }|j                  |       d{    nX|	rKt        |	d||||       d{   \  }}t        t        |||||||      }|j                  |       d{    nt        d      |s+|J |j                          |j                          d{    Y 	 |
r-|	J |	j                          |	j                          d{    yy7 7 {7 ]7 E7 7 7 7 7 7 P# |r.|J |j                          |j                          d{  7   w w xY w7 U# |
r.|	J |	j                          |	j                          d{  7   w w xY ww)a  Copy files using SCP

       This function is a coroutine which copies one or more files or
       directories using the SCP protocol. Source and destination paths
       can be `str` or `bytes` values to reference local files or can be
       a tuple of the form `(conn, path)` where `conn` is an open
       :class:`SSHClientConnection` to reference files and directories
       on a remote system.

       For convenience, a host name or tuple of the form `(host, port)`
       can be provided in place of the :class:`SSHClientConnection` to
       request that a new SSH connection be opened to a host using
       default connect arguments. A `str` or `bytes` value of the form
       `'host:path'` may also be used in place of the `(conn, path)`
       tuple to make a new connection to the requested host on the
       default SSH port.

       Either a single source path or a sequence of source paths can be
       provided, and each path can contain '*' and '?' wildcard characters
       which can be used to match multiple source files or directories.

       When copying a single file or directory, the destination path
       can be either the full path to copy data into or the path to an
       existing directory where the data should be placed. In the latter
       case, the base file name from the source path will be used as the
       destination name.

       When copying multiple files, the destination path must refer to
       a directory. If it doesn't already exist, a directory will be
       created with that name.

       If the destination path is an :class:`SSHClientConnection` without
       a path or the path provided is empty, files are copied into the
       default destination working directory.

       If preserve is `True`, the access and modification times and
       permissions of the original files and directories are set on the
       copied files. However, do to the timing of when this information
       is sent, the preserved access time will be what was set on the
       source file before the copy begins. So, the access time on the
       source file will no longer match the destination after the
       transfer completes.

       If recurse is `True` and the source path points at a directory,
       the entire subtree under that directory is copied.

       Symbolic links found on the source will have the contents of their
       target copied rather than creating a destination symbolic link.
       When using this option during a recursive copy, one needs to watch
       out for links that result in loops. SCP does not provide a
       mechanism for preserving links. If you need this, consider using
       SFTP instead.

       The block_size value controls the size of read and write operations
       issued to copy the files. It defaults to 16 KB.

       If progress_handler is specified, it will be called after each
       block of a file is successfully copied. The arguments passed to
       this handler will be the relative path of the file being copied,
       bytes copied so far, and total bytes in the file being copied. If
       multiple source paths are provided or recurse is set to `True`,
       the progress_handler will be called consecutively on each file
       being copied.

       If error_handler is specified and an error occurs during the copy,
       this handler will be called with the exception instead of it being
       raised. This is intended to primarily be used when multiple source
       paths are provided or when recurse is set to `True`, to allow
       error information to be collected without aborting the copy of the
       remaining files. The error handler can raise an exception if it
       wants the copy to completely stop. Otherwise, after an error, the
       copy will continue starting with the next file.

       If any other keyword arguments are specified, they will be passed
       to the AsyncSSH connect() call when attempting to open any new SSH
       connections needed to perform the file transfer.

       :param srcpaths:
           The paths of the source files or directories to copy
       :param dstpath: (optional)
           The path of the destination file or directory to copy into
       :param preserve: (optional)
           Whether or not to preserve the original file attributes
       :param recurse: (optional)
           Whether or not to recursively copy directories
       :param block_size: (optional)
           The block size to use for file reads and writes
       :param progress_handler: (optional)
           The function to call to report copy progress
       :param error_handler: (optional)
           The function to call when an error occurs
       :type preserve: `bool`
       :type recurse: `bool`
       :type block_size: `int`
       :type progress_handler: `callable`
       :type error_handler: `callable`

       :raises: | :exc:`OSError` if a local file I/O error occurs
                | :exc:`SFTPError` if the server returns an error
                | :exc:`ValueError` if both source and destination are local

    rd   r   NTFzLocal copy not supported)r]   rQ   rS   r   rz   r   r   r   rG  r5  r7  r)   r  ri   r   r  )rc  r  r   r   r  r  r   r   r   dstconn	close_dstr  srcconn	close_srcrH  rI  rJ  rK  copierr   r   sinkr   s                          r4   scprk    s    X 	8eS(34%(S]a-?: h-!#K(3G(Fv(F"FGWi.(G0;G0Nv0N*N'GWi%0w3@{Hgw4P .P*J
 4AXw4Q .Q*J
 (
J
(2J(8-IF !**,&&+8{Hgw,P &PNFF $Hffk$,gz$4mED ((7++++8Xw,Q &QNFF (&&(0':(8-IF !**W---$%?@@"...MMO!--///Q  T &&&MMO%%''' [ #G +O.P.Q '&P ,&Q . 0 "...MMO!--///  ( &&&MMO%%''' s  AI9G3I9&I ;G6<I HG9H7G<8+H#G?$H>H?2H1H2HH1H>H	?HI 'I :H;I )I9,I-I96I 9H<H?HHHH	HI *H?7H:
8H??I I9*I6.I1/I66I9sftp_serverr   stdinr   stdoutr   stderrc           
         	 d	 fd}	 t               j                  |      |j                  j	                  d	|d
d j                                t               }j                  r-t        |||j                  j                   dd      	 |       S t#        |||j$                  j                  j                   dd      	 |       S # t        $ r}|j                  j	                  dt        |             |j                  dt        |      j                  d      z   dz          t        d|j                        j                  d       Y d}~yd}~ww xY w)z*Return a handler for an SCP server sessionNc                     K   	 j                   j                         d{    j                          y7 # j                          w xY ww)z(Run an SCP server to handle this requestN)r5  r0   r  )rb   handlerrl  s   r4   _run_handlerz$run_scp_server.<locals>._run_handler,  s@     	++dii((( )s%   A; 9; A; AAzError starting SCP server: %sr   rZ   r   r*   r   zStarting SCP server, args: %sr   FT)r   r   r   )r   r   ri   r   r   rS   r   r   r   r  r  stripr    r   r  r   r   r7  r   )
rl  r   rm  rn  ro  rs  r`   r  rb   rr  s
   `       @@r4   run_scp_serverru  '  s$   
$$W- 
LL5wqr{7H7H7JK	k	"B {{Rt||+0? > 2ufd.>.><<uTK >'  93s8DXC 885@A055a8	s   C 	EA9EEr   )TrO   argparser   r-  pathlibr   r   r   r}   typesr   typingr   r   r   r   r	   r
   r   r   r   r   typing_extensionsr   r   	constantsr   r   r   loggingr   miscr   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r  r*   
connectionr+   streamr,   r-   rQ   rS   r{   r|   _SCPConnPathr/   r	  rR   ra   rh   rm   rr   r   r   	Namespacer   ArgumentParserr   r   r  r7  rG  rk  ru  r3   r7   r4   <module>r     s  .        
  I I 5 5 , # E  < < / I I J J K K + )/, uc8-BBC!U8X-.(BCX > (,5%*'$y/ : e_48"  -6(B B5c5#9 BK K%S/ K$.L $.h,-x=>$.N3 T %)59!%-5 	452x!! OH++ O4l1 l1^\( \(~b({ b(Jc. c.N '+d(@E#6:04	d(lH\,BBC d(#d(9=d(d(14d( !4d( .	d( DH	d(N"
 "S ","6H"-"2<T2B"r7   