1"""
2Portable file locking utilities.
3
4Based partially on an example by Jonathan Feignberg in the Python
5Cookbook [1] (licensed under the Python Software License) and a ctypes port by
6Anatoly Techtonik for Roundup [2] (license [3]).
7
8[1] https://code.activestate.com/recipes/65203/
9[2] https://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/portalocker.py # NOQA
10[3] https://sourceforge.net/p/roundup/code/ci/default/tree/COPYING.txt
11
12Example Usage::
13
14 >>> from plain.internal.files import locks
15 >>> with open('./file', 'wb') as f:
16 ... locks.lock(f, locks.LOCK_EX)
17 ... f.write('Plain')
18"""
19
20import os
21from typing import TYPE_CHECKING
22
23if TYPE_CHECKING:
24 from typing import IO
25
26
27def _fd(f: IO[bytes] | int) -> int:
28 """Get a filedescriptor from something which could be a file or an fd."""
29 if isinstance(f, int):
30 return f
31 return f.fileno()
32
33
34if os.name == "nt":
35 import msvcrt
36 from ctypes import (
37 POINTER,
38 Structure,
39 Union,
40 WinDLL,
41 byref,
42 c_int64,
43 c_ulong,
44 c_void_p,
45 sizeof,
46 )
47 from ctypes.wintypes import BOOL, DWORD, HANDLE
48
49 LOCK_SH = 0 # the default
50 LOCK_NB = 0x1 # LOCKFILE_FAIL_IMMEDIATELY
51 LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK
52
53 # --- Adapted from the pyserial project ---
54 # detect size of ULONG_PTR
55 if sizeof(c_ulong) != sizeof(c_void_p):
56 ULONG_PTR = c_int64
57 else:
58 ULONG_PTR = c_ulong
59 PVOID = c_void_p
60
61 # --- Union inside Structure by stackoverflow:3480240 ---
62 class _OFFSET(Structure):
63 _fields_ = [("Offset", DWORD), ("OffsetHigh", DWORD)]
64
65 class _OFFSET_UNION(Union):
66 _anonymous_ = ("_offset",)
67 _fields_ = (("_offset", _OFFSET), ("Pointer", PVOID))
68
69 class OVERLAPPED(Structure):
70 _anonymous_ = ("_offset_union",)
71 _fields_ = [
72 ("Internal", ULONG_PTR),
73 ("InternalHigh", ULONG_PTR),
74 ("_offset_union", _OFFSET_UNION),
75 ("hEvent", HANDLE),
76 ]
77
78 LPOVERLAPPED = POINTER(OVERLAPPED)
79
80 # --- Define function prototypes for extra safety ---
81 kernel32 = WinDLL("kernel32")
82 LockFileEx = kernel32.LockFileEx
83 LockFileEx.restype = BOOL
84 LockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, LPOVERLAPPED]
85 UnlockFileEx = kernel32.UnlockFileEx
86 UnlockFileEx.restype = BOOL
87 UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED]
88
89 def lock(f: IO[bytes] | int, flags: int) -> bool:
90 hfile = msvcrt.get_osfhandle(_fd(f))
91 overlapped = OVERLAPPED()
92 ret = LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, byref(overlapped))
93 return bool(ret)
94
95 def unlock(f: IO[bytes] | int) -> bool:
96 hfile = msvcrt.get_osfhandle(_fd(f))
97 overlapped = OVERLAPPED()
98 ret = UnlockFileEx(hfile, 0, 0, 0xFFFF0000, byref(overlapped))
99 return bool(ret)
100
101else:
102 try:
103 import fcntl
104
105 LOCK_SH = fcntl.LOCK_SH # shared lock
106 LOCK_NB = fcntl.LOCK_NB # non-blocking
107 LOCK_EX = fcntl.LOCK_EX
108 except ImportError, AttributeError:
109 # File locking is not supported.
110 LOCK_EX = LOCK_SH = LOCK_NB = 0
111
112 # Dummy functions that don't do anything.
113 def lock(f: IO[bytes] | int, flags: int) -> bool:
114 # File is not locked
115 return False
116
117 def unlock(f: IO[bytes] | int) -> bool:
118 # File is unlocked
119 return True
120
121 else:
122
123 def lock(f: IO[bytes] | int, flags: int) -> bool:
124 try:
125 fcntl.flock(_fd(f), flags)
126 return True
127 except BlockingIOError:
128 return False
129
130 def unlock(f: IO[bytes] | int) -> bool:
131 fcntl.flock(_fd(f), fcntl.LOCK_UN)
132 return True