
    Ii<U                         S r SSKJr  SSKJr  SSKrSSKrSSKrSSKJ	r	J
r
  SSKJr  SSKJr  SSKJrJrJrJrJrJrJrJrJrJrJr  SS	KJr   " S
 S\5      rg)z
SFTP file object
    )hexlify)dequeN)DEBUGio_sleep)BufferedFile)u)	CMD_CLOSECMD_READCMD_DATA	SFTPError	CMD_WRITE
CMD_STATUS	CMD_FSTAT	CMD_ATTRSCMD_FSETSTATCMD_EXTENDEDint64)SFTPAttributesc                       \ rS rSrSrSrS"S jrS rS rS#S jr	S r
S	 rS
 rS rS rS rS rS rS rS$S jrS rS rS rS rS rS%S jrS&S jrS'S jrS(S jrS rS(S jrS rS r S  r!S!r"g))SFTPFile1   z
Proxy object for a file on the remote server, in client mode SFTP.

Instances of this class may be used as context managers in the same way
that built-in Python file objects are.
i   c                    [         R                  " U 5        Xl        X l        [         R                  " XU5        SU l        SU l        SU l        0 U l        0 U l	        [        R                  " 5       U l        S U l        [        5       U l        g )NF)r   __init__sftphandle	_set_mode	pipelined_prefetching_prefetch_done_prefetch_data_prefetch_extents	threadingLock_prefetch_lock_saved_exceptionr   _reqs)selfr   r   modebufsizes        8/venv/lib/python3.13/site-packages/paramiko/sftp_file.pyr   SFTPFile.__init__=   sq    d#	t73!# !#'nn. $W
    c                 "    U R                  SS9  g )NTasync__closer'   s    r*   __del__SFTPFile.__del__K   s    4 r,   c                 "    U R                  SS9  g)z
Close the file.
Fr.   Nr0   r2   s    r*   closeSFTPFile.closeN   s     	5!r,   c           
      f   U R                   (       a  g U R                  R                  [        SR	                  [        [        U R                  5      5      5      5        U R                  (       a  U R                  R                  U 5        [        R                  " U 5         U(       a5  U R                  R                  [        S 5      [        U R                  5        g U R                  R                  [        U R                  5        g ! [          a     g ["        [$        R&                  4 a     g f = f)Nz	close({}))_closedr   _logr   formatr   r   r   r   _finish_responsesr   r6   _async_requesttyper	   _requestEOFErrorIOErrorsocketerror)r'   r/   s     r*   r1   SFTPFile._closeT   s     <<		uk0074;;3G1HIJ>>II''-4 	 		((dYL		""9dkk: 	& 		s   !;D *D 
D0D0/D0c                 4   [        U R                  R                  5       5       Vs/ s H  o3S   U::  d  M  UPM     nn[        U5      S:X  a  gUR	                  S S9  US   u  pVXV-   U::  a  gXV-   X-   :  a  gU R                  XV-   X-   U-
  U-
  5      $ s  snf )Nr   Fc                     U S   $ Nr    )xs    r*   <lambda>5SFTPFile._data_in_prefetch_requests.<locals>.<lambda>v   s    QqTr,   )keyT)listr!   valueslensort_data_in_prefetch_requests)r'   offsetsizerI   k
buf_offsetbuf_sizes          r*   rR   #SFTPFile._data_in_prefetch_requestsp   s    D2299;<
<!!A< 	
 
 q6Q;	>" u
 F* FM1 ..!6=:#=#H
 	

s
   BBc                     U R                   R                  5        Vs/ s H  o"U::  d  M
  UPM     nn[        U5      S:X  a  g[        U5      nX-
  nU[        U R                   U   5      :  a  gU$ s  snf )z
if a block of data is present in the prefetch buffers, at the given
offset, return the offset of the relevant prefetch buffer.  otherwise,
return None.  this guarantees nothing about the number of bytes
collected in the prefetch buffer so far.
r   N)r    keysrP   max)r'   rS   irU   indexrV   s         r*   _data_in_prefetch_buffers"SFTPFile._data_in_prefetch_buffers   sq     ++002B216kQ2Bq6Q;A^
T00788 Cs
   	A0A0c                     U R                  U R                  5      nUb  OOU R                  (       d  U R                  (       a  O,U R                  R                  5         U R                  5         Mn  Uc  SU l        gU R                  U   nU R                  U	 U R                  U-
  nUS:  a  USU U R                  U'   X4S nU[        U5      :  a#  X1S U R                  U R                  U-   '   USU nU$ )z
read data out of the prefetch buffer, if possible.  if the data isn't
in the buffer, return None.  otherwise, behaves like a normal read.
NFr   )
r^   _realposr   r9   r   _read_response_check_exceptionr   r    rP   )r'   rT   rS   prefetchrV   s        r*   _read_prefetchSFTPFile._read_prefetch   s     33DMMBF!""dllII$$&!!#  > %D&&v.']]V+
>*2;J*?D',H#h-8@D 45Hr,   c                 X   [        XR                  5      nU R                  (       a  U R                  U5      nUb  U$ U R                  R                  [        U R                  [        U R                  5      [        U5      5      u  p4U[        :w  a  [        S5      eUR                  5       $ )NExpected data)minMAX_REQUEST_SIZEr   re   r   r?   r
   r   r   ra   intr   r   
get_string)r'   rT   datatmsgs        r*   _readSFTPFile._read   s    4../&&t,D##dkk5#7T
 =O,,~~r,   c           	         [        [        U5      U R                  5      nU R                  R	                  [        S 5      [        U R                  [        U R                  5      US U 5      nU R                  R                  U5        U R                  (       aB  [        U R                  5      S:  a  U R                  R                  R                  5       (       a  [        U R                  5      (       ah  U R                  R                  5       nU R                  R!                  U5      u  pVU["        :w  a  [%        S5      e[        U R                  5      (       a  Mh  U$ )Nd   zExpected status)ri   rP   rj   r   r=   r>   r   r   r   ra   r&   appendr   sock
recv_readypopleftrb   r   r   )r'   rm   chunksftp_async_requestreqrn   ro   s          r*   _writeSFTPFile._write   s    CIt445!YY55JKK$-- %L
 	

,-~~

Oc!diinn&?&?&A&Adjj//jj((*11#6
?#$566	 djj// r,   c                 N    U R                   R                  R                  U5        g)a  
Set a timeout on read/write operations on the underlying socket or
ssh `.Channel`.

:param float timeout:
    seconds to wait for a pending read/write operation before raising
    ``socket.timeout``, or ``None`` for no timeout

.. seealso:: `.Channel.settimeout`
N)r   ru   
settimeout)r'   timeouts     r*   r~   SFTPFile.settimeout   s     			!!'*r,   c                 J    U R                   R                  R                  5       $ )z
Returns the timeout in seconds (as a `float`) associated with the
socket or ssh `.Channel` used for this file.

.. seealso:: `.Channel.gettimeout`
)r   ru   
gettimeoutr2   s    r*   r   SFTPFile.gettimeout   s     yy~~((**r,   c                 N    U R                   R                  R                  U5        g)z
Set blocking or non-blocking mode on the underiying socket or ssh
`.Channel`.

:param int blocking:
    0 to set non-blocking mode; non-0 to set blocking mode.

.. seealso:: `.Channel.setblocking`
N)r   ru   setblocking)r'   blockings     r*   r   SFTPFile.setblocking   s     			""8,r,   c                     g)z
Check if the file supports random access.

:return:
    `True` if the file supports random access. If `False`,
    :meth:`seek` will raise an exception
TrH   r2   s    r*   seekableSFTPFile.seekable   s     r,   c                 (   U R                  5         X R                  :X  a  U=U l        U l        OUX R                  :X  a'  U =R                  U-  sl        U R                  U l        OU R                  5       U-   =U l        U l        [        5       U l        g)z@
Set the file's current position.

See `file.seek` for details.
N)flushSEEK_SETra   _posSEEK_CUR	_get_sizebytes_rbuffer)r'   rS   whences      r*   seekSFTPFile.seek  sk     	

]]"(..DMDI}}$III IIDM(,(86(AADMDIr,   c                     U R                   R                  [        U R                  5      u  pU[        :w  a  [        S5      e[        R                  " U5      $ )z
Retrieve information about this file from the remote system.  This is
exactly like `.SFTPClient.stat`, except that it operates on an
already-open file.

:returns:
    an `.SFTPAttributes` object containing attributes about this file.
zExpected attributes)r   r?   r   r   r   r   r   	_from_msg)r'   rn   ro   s      r*   statSFTPFile.stat  sD     ##It{{;	>122'',,r,   c                     U R                   R                  [        SR                  [	        U R
                  5      U5      5        [        5       nXl        U R                   R                  [        U R
                  U5        g)z
Change the mode (permissions) of this file.  The permissions are
unix-style and identical to those used by Python's `os.chmod`
function.

:param int mode: new permissions
zchmod({}, {!r})N)
r   r:   r   r;   r   r   r   st_moder?   r   )r'   r(   attrs      r*   chmodSFTPFile.chmod   sY     			$++GDKK,@$G	
 		<d;r,   c                    U R                   R                  [        SR                  [	        U R
                  5      X5      5        [        5       nXsUl        Ul        U R                   R                  [        U R
                  U5        g)a  
Change the owner (``uid``) and group (``gid``) of this file.  As with
Python's `os.chown` function, you must pass both arguments, so if you
only want to change one, use `stat` first to retrieve the current
owner and group.

:param int uid: new owner's uid
:param int gid: new group id
zchown({}, {!r}, {!r})N)r   r:   r   r;   r   r   r   st_uidst_gidr?   r   )r'   uidgidr   s       r*   chownSFTPFile.chown/  sb     			#**74;;+?J	
 #& T[		<d;r,   c                 l   Uc*  [         R                   " 5       [         R                   " 5       4nU R                  R                  [        SR	                  [        U R                  5      U5      5        [        5       nUu  Ul        Ul	        U R                  R                  [        U R                  U5        g)a  
Set the access and modified times of this file.  If
``times`` is ``None``, then the file's access and modified times are
set to the current time.  Otherwise, ``times`` must be a 2-tuple of
numbers, of the form ``(atime, mtime)``, which is used to set the
access and modified times, respectively.  This bizarre API is mimicked
from Python for the sake of consistency -- I apologize.

:param tuple times:
    ``None`` or a tuple of (access time, modified time) in standard
    internet epoch time (seconds since 01 January 1970 GMT)
Nzutime({}, {!r}))timer   r:   r   r;   r   r   r   st_atimest_mtimer?   r   )r'   timesr   s      r*   utimeSFTPFile.utimeA  s}     =YY[$))+.E		$++GDKK,@%H	
 ',$t}		<d;r,   c                     U R                   R                  [        SR                  [	        U R
                  5      U5      5        [        5       nXl        U R                   R                  [        U R
                  U5        g)z
Change the size of this file.  This usually extends
or shrinks the size of the file, just like the ``truncate()`` method on
Python file objects.

:param size: the new size of the file
ztruncate({}, {!r})N)
r   r:   r   r;   r   r   r   st_sizer?   r   )r'   rT   r   s      r*   truncateSFTPFile.truncateW  sY     			'..wt{{/CTJ	
 		<d;r,   c           
          U R                   R                  [        SU R                  U[	        U5      [	        U5      U5      u  pVUR                  5         UR                  5         UR                  5       nU$ )a  
Ask the server for a hash of a section of this file.  This can be used
to verify a successful upload or download, or for various rsync-like
operations.

The file is hashed from ``offset``, for ``length`` bytes.
If ``length`` is 0, the remainder of the file is hashed.  Thus, if both
``offset`` and ``length`` are zero, the entire file is hashed.

Normally, ``block_size`` will be 0 (the default), and this method will
return a byte string representing the requested hash (for example, a
string of length 16 for MD5, or 20 for SHA-1).  If a non-zero
``block_size`` is given, each chunk of the file (from ``offset`` to
``offset + length``) of ``block_size`` bytes is computed as a separate
hash.  The hash results are all concatenated and returned as a single
string.

For example, ``check('sha1', 0, 1024, 512)`` will return a string of
length 40.  The first 20 bytes will be the SHA-1 of the first 512 bytes
of the file, and the last 20 bytes will be the SHA-1 of the next 512
bytes.

:param str hash_algorithm:
    the name of the hash algorithm to use (normally ``"sha1"`` or
    ``"md5"``)
:param offset:
    offset into the file to begin hashing (0 means to start from the
    beginning)
:param length:
    number of bytes to hash (0 means continue to the end of the file)
:param int block_size:
    number of bytes to hash per result (must not be less than 256; 0
    means to compute only one hash of the entire segment)
:return:
    `str` of bytes representing the hash of each block, concatenated
    together

:raises:
    ``IOError`` -- if the server doesn't support the "check-file"
    extension, or possibly doesn't support the hash algorithm requested

.. note:: Many (most?) servers don't support this extension yet.

.. versionadded:: 1.4
z
check-file)r   r?   r   r   r   get_textget_remainder)r'   hash_algorithmrS   length
block_sizern   ro   rm   s           r*   checkSFTPFile.checkf  sc    \ ##KK&M&M
 	  "r,   c                     Xl         g)ah  
Turn on/off the pipelining of write operations to this file.  When
pipelining is on, paramiko won't wait for the server response after
each write operation.  Instead, they're collected as they come in. At
the first non-write operation (including `.close`), all remaining
server responses are collected.  This means that if there was an error
with one of your later writes, an exception might be thrown from within
`.close` instead of `.write`.

By default, files are not pipelined.

:param bool pipelined:
    ``True`` if pipelining should be turned on for this file; ``False``
    otherwise

.. versionadded:: 1.5
N)r   )r'   r   s     r*   set_pipelinedSFTPFile.set_pipelined  s	    $ #r,   Nc                    Uc  U R                  5       R                  n/ nU R                  nXA:  a5  [        U R                  X-
  5      nUR                  XE45        XE-  nXA:  a  M5  [        U5      S:  a  U R                  X25        gg)ae  
Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls.  If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementally buffered in a background thread.

The prefetched data is stored in a buffer until read via the `.read`
method.  Once data has been read, it's removed from the buffer.  The
data may be read in a random order (using `.seek`); chunks of the
buffer that haven't been read will continue to be buffered.

:param int file_size:
    When this is ``None`` (the default), this method calls `stat` to
    determine the remote file size. In some situations, doing so can
    cause exceptions or hangs (see `#562
    <https://github.com/paramiko/paramiko/pull/562>`_); as a
    workaround, one may call `stat` explicitly and pass its value in
    via this parameter.
:param int max_concurrent_requests:
    The maximum number of concurrent read requests to prefetch. See
    `.SFTPClient.get` (its ``max_concurrent_prefetch_requests`` param)
    for details.

.. versionadded:: 1.5.1
.. versionchanged:: 1.16.0
    The ``file_size`` parameter was added (with no default value).
.. versionchanged:: 1.16.1
    The ``file_size`` parameter was made optional for backwards
    compatibility.
.. versionchanged:: 3.3
    Added ``max_concurrent_requests``.
Nr   )r   r   ra   ri   rj   rt   rP   _start_prefetch)r'   	file_sizemax_concurrent_requestschunksnrx   s         r*   rd   SFTPFile.prefetch  s    B 		++I MMm--y}=EMM1*%JA m v;?  A r,   c              #     #    U R                   R                  [        SR                  [	        U R
                  5      U5      5        / nU Hr  u  pEU R                  U5      (       d  U R                  XE5      (       a  M3  US:  d  M;  [        XPR                  5      nUR                  XF45        XF-  nXV-  nUS:  a  M7  Mt     U R                  X25        U H-  nU R                  US   5        U R                  US   5      v   M/     g7f)a  
Read a set of blocks from the file by (offset, length).  This is more
efficient than doing a series of `.seek` and `.read` calls, since the
prefetch machinery is used to retrieve all the requested blocks at
once.

:param chunks:
    a list of ``(offset, length)`` tuples indicating which sections of
    the file to read
:param int max_concurrent_prefetch_requests:
    The maximum number of concurrent read requests to prefetch. See
    `.SFTPClient.get` (its ``max_concurrent_prefetch_requests`` param)
    for details.
:return: a list of blocks read, in the same order as in ``chunks``

.. versionadded:: 1.5.4
.. versionchanged:: 3.3
    Added ``max_concurrent_prefetch_requests``.
zreadv({}, {!r})r      N)r   r:   r   r;   r   r   r^   rR   ri   rj   rt   r   r   read)r'   r    max_concurrent_prefetch_requestsread_chunksrS   rT   
chunk_sizerI   s           r*   readvSFTPFile.readv  s     ( 			$++GDKK,@&I	
 "LF-- 00>> ( '<'<=
""F#78$"	 ( # 	[KAIIadO))AaD/! s   A?D5D<A	Dc                 F     U R                  5       R                  $ !    g= frG   )r   r   r2   s    r*   r   SFTPFile._get_size  s#    	99;&&&	s     c                     SU l         SU l        [        R                  " U R                  X4S9nSUl        UR                  5         g )NTF)targetargs)r   r   r"   Thread_prefetch_threaddaemonstart)r'   r   r   rn   s       r*   r   SFTPFile._start_prefetch  sC     #((2
 		r,   c           
         U H  u  p4UbW   U R                      [        U R                  5      nXR:  a
   S S S 5        O% S S S 5        [        R                  " [
        5        MV  U R                  R                  U [        U R                  [        U5      [        U5      5      nU R                      X44U R                  U'   S S S 5        M     g ! , (       d  f       N= f! , (       d  f       M  = fN)r$   rP   r!   r   sleepr   r   r=   r
   r   r   rk   )r'   r   r   rS   r   pf_lennums          r*   r   SFTPFile._prefetch_thread$  s     %NF&2,,!$T%;%;!<!;! -,; - JJx(  ))**hU6]CKC $$/5.>&&s+ %$ % -, %$s   C-C
C	
C+	c                    U[         :X  a   U R                  R                  U5        g U[
        :w  a  [        S5      eUR                  5       n U R                     X0R                  ;   aV  U R                  U   u  pgXPR                  U'   U R                  U	 [        U R                  5      S:X  a  SU l         S S S 5        g  S S S 5        M}  ! [         a  nX@l         S nAg S nAff = f! , (       d  f       N-= f)Nrh   Tr   )r   r   _convert_status	Exceptionr%   r   r   rl   r$   r!   r    rP   r   )r'   rn   ro   r   erm   rS   r   s           r*   _async_responseSFTPFile._async_response7  s    
?*		))#. =O,,~~$$000%)%;%;C%@NF26''/..s34112a7.2+ %$0 %   *()%%* %$s$   C AC(
C%C  C%(
C6c                 H    U R                   b  U R                   nSU l         Ueg)z.if there's a saved exception, raise & clear itN)r%   )r'   rI   s     r*   rc   SFTPFile._check_exceptionM  s+      ,%%A$(D!G -r,   )r   r    r   r!   r$   r   r   ra   r&   r%   r   r   r   )rrM   )F)r   )r   r   r   )T)NNr   )#__name__
__module____qualname____firstlineno____doc__rj   r   r3   r6   r1   rR   r^   re   rp   r{   r~   r   r   r   r   r   r   r   r   r   r   r   rd   r   r   r   r   r   rc   __static_attributes__rH   r,   r*   r   r   1   s     !"8
("< ,++
-  -<<$<,<:x#(,B\+"^	?&,r,   r   )r   binasciir   collectionsr   rB   r"   r   paramiko.commonr   r   paramiko.filer   paramiko.utilr   paramiko.sftpr	   r
   r   r   r   r   r   r   r   r   r   paramiko.sftp_attrr   r   rH   r,   r*   <module>r      sK   &
      + &     .a| ar,   