
    \j=                    d	   U d dl mZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
 ddlmZ ddlmZmZ ej                   d	k(  rad dlZd dlZd d
lmZ dZded<   dZded<   dZded<   eez  ez  Zded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZded<   dZ ded <   eez  e z  Z!ded!<   dZ"ded"<   dZ#ded#<   dZ$ded$<   d%Z%ded&<   d'Z&ded(<   d Z'ded)<   d*Z(ded+<   d,Z)ded-<   d.Z*ded/<    ejV                  d0      Z,d1ed2<    ejV                  d3d45      Z-d1ed6<    G d7 d8ej\                        Z/ G d9 d:ej\                        Z0 G d; d<ej\                        Z1 G d= d>ej\                        Z2 G d? d@ej\                        Z3ejh                  e,jj                  _6         ejn                  ejp                        ejr                   ejn                  e0       ejn                  e1       ejn                  ejt                        ejv                  ejv                  ejv                  ejv                  ejx                  ejv                  ge,jj                  _=        ejh                  e,j|                  _6        ej~                   ejn                  e/      ejx                  ejx                  ge,j|                  _=        de,j                  _6         ejn                  e/      ge,j                  _=        ejv                  e,j                  _6        ejh                  ge,j                  _=        ejp                  ge-j                  _=        ej                  e-j                  _6        ejp                   ejn                  e3      ge-j                  _=        ej                  e-j                  _6        ejp                  ejr                  ejr                  ejr                  ejr                   ejn                  e2      ge-j                  _=        ej                  e-j                  _6        ejp                  ejr                  ejr                  ejr                   ejn                  e2      ge-j                  _=        ej                  e-j                  _6        dHdAZGdIdBZH G dC dDe      ZIdJdEZJdKdFZKdDgZLy G dG dDe      ZIdDgZLy)L    )annotationsN)suppress)Path)Finalcast   )BaseFileLock)ensure_directory_existsraise_on_not_writable_filewin32)wintypesl        z
Final[int]_GENERIC_READi   @_GENERIC_WRITEi   _SYNCHRONIZE_DESIRED_ACCESS   _FILE_SHARE_READ_WRITE_FILE_OPEN_IF_FILE_ATTRIBUTE_READONLY   _FILE_ATTRIBUTE_NORMALi   _FILE_ATTRIBUTE_REPARSE_POINT    _FILE_SYNCHRONOUS_IO_NONALERT@   _FILE_NON_DIRECTORY_FILEi    _FILE_OPEN_REPARSE_POINT_CREATE_OPTIONS_OBJ_CASE_INSENSITIVE_OWNER_WRITE_LOCKFILE_FAIL_IMMEDIATELY   _LOCKFILE_EXCLUSIVE_LOCK!   _ERROR_LOCK_VIOLATION_STATUS_SUCCESSl   "    _STATUS_ACCESS_DENIEDl   C    _STATUS_SHARING_VIOLATIONl   V    _STATUS_DELETE_PENDINGntdllzFinal[ctypes.WinDLL]_ntdllkernel32T)use_last_error	_kernel32c                  ^    e Zd Zdej                  fdej                  fdej
                  ffZy)_UNICODE_STRINGLengthMaximumLengthBufferN)__name__
__module____qualname__r   USHORTLPWSTR_fields_     D/root/.hermes/venv/lib/python3.12/site-packages/filelock/_windows.pyr0   r0   8   s-    x'hoo.x'
r;   r0   c                      e Zd Zdej                  fdej
                  fd ej                  e      fdej                  fdej                  fdej                  ffZ
y)_OBJECT_ATTRIBUTESr1   RootDirectory
ObjectName
AttributesSecurityDescriptorSecurityQualityOfServiceN)r4   r5   r6   r   ULONGHANDLEctypesPOINTERr0   c_void_pr9   r:   r;   r<   r>   r>   ?   sX    x~~&hoo.>6>>/:;8>>*!6??3'9
r;   r>   c                  D    e Zd Zdej                  fdej                  ffZy)_IO_STATUS_BLOCKStatusInformationN)r4   r5   r6   rF   rH   r9   r:   r;   r<   rJ   rJ   I   s!    v'FOO,
r;   rJ   c                      e Zd Zdej                  fdej                  fdej                  fdej                  fdej                  ffZy)_OVERLAPPEDInternalInternalHighOffset
OffsetHighhEventN)	r4   r5   r6   rF   rH   r   DWORDrE   r9   r:   r;   r<   rN   rN   O   sE    )V__-x~~&8>>*x'
r;   rN   c                     e Zd Zdej                  fdej
                  fdej
                  fdej
                  fdej                  fdej                  fdej                  fdej                  fd	ej                  fd
ej                  ff
Zy)_BY_HANDLE_FILE_INFORMATIONdwFileAttributesftCreationTimeftLastAccessTimeftLastWriteTimedwVolumeSerialNumbernFileSizeHighnFileSizeLownNumberOfLinksnFileIndexHighnFileIndexLowN)r4   r5   r6   r   rT   FILETIMEr9   r:   r;   r<   rV   rV   X   s    0x001!2!23 1 12#X^^4hnn-X^^,x~~.x~~.hnn-
r;   rV   c           
        t               }t        t        z  }t        j	                  t        j                  |       |dddt        j                  |            ryt        j                         }|t        k(  ryt        j                  |      )Nr   r   TF)rN   r#   r!   r.   
LockFileExmsvcrtget_osfhandlerF   byrefget_last_errorr%   WinError)fd
overlappedflagserrs       r<   _lock_fd_nonblockingrm      so     !]
(+EE 4 4R 8%Aq&,,WaJbc##%''ooc""r;   c           	         t               }t        j                  t        j                  |       dddt        j                  |            s't        j                  t        j                               y )Nr   r   )	rN   r.   UnlockFileExrd   re   rF   rf   rh   rg   )ri   rj   s     r<   
_unlock_fdrp      sR     ]
%%f&:&:2&>1aV`Iab//&"7"7"9:: cr;   c                       e Zd ZdZddZddZy)WindowsFileLockay  
        Uses ``LockFileEx`` to hard lock a byte range of the lock file on Windows systems.

        Lock file cleanup: Windows attempts to delete the lock file after release, but deletion is
        not guaranteed in multi-threaded scenarios where another thread holds an open handle. The lock
        file may persist on disk, which does not affect lock correctness.
        c                Z   t        | j                         t        | j                         t        | j                  | j	                               }|y 	 t        |      }|r| j                  |       |st        j                  |       y y # t        $ r t        j                  |        w xY wN)
r   	lock_filer
   _open_non_reparse_fd
_open_moderm   _mark_descriptor_ownedBaseExceptionosclose)selfri   lockeds      r<   _acquirezWindowsFileLock._acquire   s    &t~~6#DNN3 &dnndoo6GHBz-b1//3   ! s   B
 
 B*c                H   t        d| j                  j                        }t        |       | j	                          | j                  |d       | j                  s<t        t              5  t        | j                        j                          d d d        y y # 1 sw Y   y xY w)NintF)default_suppresses)r   _contextlock_file_fdrp   _mark_descriptor_released_close_released_fd_preserve_lock_filer   OSErrorr   ru   unlink)r|   ri   s     r<   _releasezWindowsFileLock._release   s    eT]]778B rN**,##B5#A++g& 2(//12 2 ,2 2s   *$BB!NreturnNoner4   r5   r6   __doc__r~   r   r:   r;   r<   rr   rr      s    		&
	2r;   rr   c                \   t        j                  d| dt        j                  t        j                  z         t        | |t        z         \  }}|t        k7  rS|t        t        hv ryt        j                  |      }t        dt        j                  |      j                         | |      t!               }t"        j%                  |t        j&                  |            s>t        j(                         }t"        j+                  |       t        j,                  |      |j.                  t0        z  r%t"        j+                  |       d|  }t        |      	 t3        j4                  |t        j                  t        j6                  z        S # t8        $ r t"        j+                  |        w xY w)a  
        Open *path* for locking while refusing reparse points, bound to the handle actually locked.

        The file is opened through ``NtCreateFile`` with ``FILE_OPEN_REPARSE_POINT`` so a symlink or junction planted
        at the path is not followed, and the reparse decision is read from *that* handle via
        ``GetFileInformationByHandle`` rather than from a prior pathname query. Reading the held handle closes the
        check-then-open race: an attacker cannot swap the path between validation and use because both act on the same
        handle. Share mode omits delete so a peer cannot unlink or rename the file out from under a live holder,
        matching ``os.open``'s ``_SH_DENYNO``.

        ``NtCreateFile`` is used instead of ``CreateFileW`` because its return value carries the raw ``NTSTATUS``.
        Windows collapses a transient delete-pending name and a permanent access denial into the same Win32
        ``ERROR_ACCESS_DENIED``; the status keeps them apart, so a real denial fails fast instead of spinning until the
        caller's timeout (#604).

        The reparse option only guards the final path component; Windows still follows reparse points in intermediate
        directories. This assumes the lock file sits in a lock directory untrusted users cannot modify. A path with
        attacker-controlled parent directories would need component-by-component handle validation.

        :param path: the lock file path.
        :param mode: the permission mode; as ``os.open`` does on Windows, a cleared owner-write bit creates the file
            read-only. The attribute only takes effect when the file is created, not when an existing one is opened.

        :returns: a file descriptor owning the opened handle, or ``None`` on a sharing violation or a delete-pending
            name the caller should treat as contention and retry.

        :raises OSError: if the path resolves to a reparse point, or the open fails for any other reason, raised with
            the Win32 error the status maps to.

        openN)	read_onlyz1Lock file is a reparse point (symlink/junction): )sysauditrz   O_RDWRO_CREAT_nt_openr    r&   r(   r)   r+   RtlNtStatusToDosErrorr   rF   FormatErrorstriprV   r.   GetFileInformationByHandlerf   rg   CloseHandlerh   rW   r   rd   open_osfhandleO_NOINHERITry   )pathmodehandlestatuswinerrorinforl   msgs           r<   rv   rv      sO   @ 			&$bii"**&<=!$d\6I2IJ_$35KLL33F;H$ 2 28 < B B DdHUU*,33FFLL<NO'')C!!&)//#&&  #@@!!&)EdVLC#,	((R^^1KLL 	!!&)	s   4F  F+c               :   t               }t        j                  | t        j                  |      dd      dz  }|t
        k7  rd|fS 	 t               }t        j                  t              |_        t        j                  |      |_
        t        |_        t        j                         }t               }t        j!                  t        j                  |      t"        t        j                  |      t        j                  |      d|rt$        nt&        t(        t*        t,        dd      dz  }t        j/                  t        j                  |             |t
        k7  rd|fS |j0                  xs d|fS # t        j/                  t        j                  |             w xY w)a  
        Open *path* through ``NtCreateFile`` and return ``(handle, status)``.

        ``RtlDosPathNameToNtPathName_U_WithStatus`` translates the Win32 path to the NT namespace, handling relative,
        drive, UNC and extended-length path forms as Win32 itself would, and allocates a buffer that
        ``RtlFreeUnicodeString`` releases. The handle is ``0`` unless the status is ``STATUS_SUCCESS``.
        Nl    r   )r0   r+   'RtlDosPathNameToNtPathName_U_WithStatusrF   rf   r&   r>   sizeofr1   pointerr@   r   rA   r   rE   rJ   NtCreateFiler   r   r   r   r   r   RtlFreeUnicodeStringvalue)r   r   nt_namer   
attributesr   	io_statuss          r<   r   r   	  sK    "#??fllSZF[]acghkuu_$f9	?+-J &.@ AJ$*NN7$;J!$9J!__&F(*I##LL(#LL,LL+09,?U*!#  " ''W(=>_$f9|| q&(( ''W(=>s   C"E0 0*Fc                       e Zd ZdZddZddZy)rr   zRUses ``LockFileEx`` to hard lock a byte range of the lock file on Windows systems.c                    t         rt   NotImplementedErrorr|   s    r<   r~   zWindowsFileLock._acquire7      %%r;   c                    t         rt   r   r   s    r<   r   zWindowsFileLock._release:  r   r;   Nr   r   r:   r;   r<   rr   rr   4  s    `	&	&r;   )ri   r   r   bool)ri   r   r   r   )r   strr   r   r   z
int | None)r   r   r   r   r   ztuple[int, int])M
__future__r   rz   r   
contextlibr   pathlibr   typingr   r   _apir	   _utilr
   r   platformrF   rd   r   r   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r#   r%   r&   r'   r(   r)   WinDLLr+   r.   	Structurer0   r>   rJ   rN   rV   LONGr   restyperG   rE   rT   
c_longlongrD   rH   argtypesr   LPCWSTRr   r   r   BOOLr   rc   ro   rm   rp   rr   rv   r   __all__r:   r;   r<   <module>r      sA   " 	 
     F<<7 *M:*!+NJ+)L*)"/."@<"OOZO J  !"M:!+5j5)3J30:!:: 1;!::+5j5+5j5"?BZ"Z]u"uOZu(2:2$L*$ .8
7+5j5(*:*
 #-OZ,(2:2,6z6)3J3#06==#9F 9&3fmmJt&TI#T
&** 

V-- 

6++ 

f&& 

f&6&6 
 #+--Fx')*'(v(()$F  >F]]F22:'	?F22; +/F',:FNN?,K+LF(+3>>F  (-5]]OF  )&.oo%6I"$,MMI!5=__nfnnUpFq4rI((13;==I((0{#%I! $,==I {#'I# &.]]I"#;
&2, &2P7r')l &, & r;   