storage.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2016 Guillaume Ayoub
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. """
  18. Storage backends.
  19. This module loads the storage backend, according to the storage configuration.
  20. Default storage uses one folder per collection and one file per collection
  21. entry.
  22. """
  23. import errno
  24. import json
  25. import os
  26. import posixpath
  27. import shutil
  28. import stat
  29. import threading
  30. import time
  31. from contextlib import contextmanager
  32. from hashlib import md5
  33. from importlib import import_module
  34. from itertools import groupby
  35. from random import getrandbits
  36. from tempfile import TemporaryDirectory
  37. from atomicwrites import AtomicWriter
  38. import vobject
  39. if os.name == "nt":
  40. import ctypes
  41. import ctypes.wintypes
  42. import msvcrt
  43. LOCKFILE_EXCLUSIVE_LOCK = 2
  44. if ctypes.sizeof(ctypes.c_void_p) == 4:
  45. ULONG_PTR = ctypes.c_uint32
  46. else:
  47. ULONG_PTR = ctypes.c_uint64
  48. class Overlapped(ctypes.Structure):
  49. _fields_ = [
  50. ("internal", ULONG_PTR),
  51. ("internal_high", ULONG_PTR),
  52. ("offset", ctypes.wintypes.DWORD),
  53. ("offset_high", ctypes.wintypes.DWORD),
  54. ("h_event", ctypes.wintypes.HANDLE)]
  55. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  56. lock_file_ex.argtypes = [
  57. ctypes.wintypes.HANDLE,
  58. ctypes.wintypes.DWORD,
  59. ctypes.wintypes.DWORD,
  60. ctypes.wintypes.DWORD,
  61. ctypes.wintypes.DWORD,
  62. ctypes.POINTER(Overlapped)]
  63. lock_file_ex.restype = ctypes.wintypes.BOOL
  64. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  65. unlock_file_ex.argtypes = [
  66. ctypes.wintypes.HANDLE,
  67. ctypes.wintypes.DWORD,
  68. ctypes.wintypes.DWORD,
  69. ctypes.wintypes.DWORD,
  70. ctypes.POINTER(Overlapped)]
  71. unlock_file_ex.restype = ctypes.wintypes.BOOL
  72. elif os.name == "posix":
  73. import fcntl
  74. def load(configuration, logger):
  75. """Load the storage manager chosen in configuration."""
  76. storage_type = configuration.get("storage", "type")
  77. if storage_type == "multifilesystem":
  78. collection_class = Collection
  79. else:
  80. collection_class = import_module(storage_type).Collection
  81. class CollectionCopy(collection_class):
  82. """Collection copy, avoids overriding the original class attributes."""
  83. CollectionCopy.configuration = configuration
  84. CollectionCopy.logger = logger
  85. return CollectionCopy
  86. def get_etag(text):
  87. """Etag from collection or item."""
  88. etag = md5()
  89. etag.update(text.encode("utf-8"))
  90. return '"%s"' % etag.hexdigest()
  91. def get_uid(item):
  92. """UID value of an item if defined."""
  93. return hasattr(item, "uid") and item.uid.value
  94. def sanitize_path(path):
  95. """Make path absolute with leading slash to prevent access to other data.
  96. Preserve a potential trailing slash.
  97. """
  98. trailing_slash = "/" if path.endswith("/") else ""
  99. path = posixpath.normpath(path)
  100. new_path = "/"
  101. for part in path.split("/"):
  102. if not part or part in (".", ".."):
  103. continue
  104. new_path = posixpath.join(new_path, part)
  105. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  106. return new_path + trailing_slash
  107. def is_safe_path_component(path):
  108. """Check if path is a single component of a path.
  109. Check that the path is safe to join too.
  110. """
  111. return path and "/" not in path and path not in (".", "..")
  112. def is_safe_filesystem_path_component(path):
  113. """Check if path is a single component of a filesystem path.
  114. Check that the path is safe to join too.
  115. """
  116. return (
  117. path and not os.path.splitdrive(path)[0] and
  118. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  119. not path.startswith(".") and not path.endswith("~"))
  120. def path_to_filesystem(root, *paths):
  121. """Convert path to a local filesystem path relative to base_folder.
  122. `root` must be a secure filesystem path, it will be prepend to the path.
  123. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  124. """
  125. paths = [sanitize_path(path).strip("/") for path in paths]
  126. safe_path = root
  127. for path in paths:
  128. if not path:
  129. continue
  130. for part in path.split("/"):
  131. if not is_safe_filesystem_path_component(part):
  132. raise UnsafePathError(part)
  133. safe_path = os.path.join(safe_path, part)
  134. return safe_path
  135. def sync_directory(path):
  136. """Sync directory to disk.
  137. This only works on POSIX and does nothing on other systems.
  138. """
  139. if os.name == "posix":
  140. fd = os.open(path, 0)
  141. try:
  142. if hasattr(fcntl, "F_FULLFSYNC"):
  143. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  144. else:
  145. os.fsync(fd)
  146. finally:
  147. os.close(fd)
  148. class UnsafePathError(ValueError):
  149. def __init__(self, path):
  150. message = "Can't translate name safely to filesystem: %s" % path
  151. super().__init__(message)
  152. class ComponentExistsError(ValueError):
  153. def __init__(self, path):
  154. message = "Component already exists: %s" % path
  155. super().__init__(message)
  156. class ComponentNotFoundError(ValueError):
  157. def __init__(self, path):
  158. message = "Component doesn't exist: %s" % path
  159. super().__init__(message)
  160. class EtagMismatchError(ValueError):
  161. def __init__(self, etag1, etag2):
  162. message = "ETags don't match: %s != %s" % (etag1, etag2)
  163. super().__init__(message)
  164. class _EncodedAtomicWriter(AtomicWriter):
  165. def __init__(self, path, encoding, mode="w", overwrite=True):
  166. self._encoding = encoding
  167. return super().__init__(path, mode, overwrite=True)
  168. def get_fileobject(self, **kwargs):
  169. return super().get_fileobject(
  170. encoding=self._encoding, prefix=".Radicale.tmp-", **kwargs)
  171. class Item:
  172. def __init__(self, collection, item, href, last_modified=None):
  173. self.collection = collection
  174. self.item = item
  175. self.href = href
  176. self.last_modified = last_modified
  177. def __getattr__(self, attr):
  178. return getattr(self.item, attr)
  179. @property
  180. def etag(self):
  181. return get_etag(self.serialize())
  182. class BaseCollection:
  183. # Overriden on copy by the "load" function
  184. configuration = None
  185. logger = None
  186. def __init__(self, path, principal=False):
  187. """Initialize the collection.
  188. ``path`` must be the normalized relative path of the collection, using
  189. the slash as the folder delimiter, with no leading nor trailing slash.
  190. """
  191. raise NotImplementedError
  192. @classmethod
  193. def discover(cls, path, depth="0"):
  194. """Discover a list of collections under the given ``path``.
  195. If ``depth`` is "0", only the actual object under ``path`` is
  196. returned.
  197. If ``depth`` is anything but "0", it is considered as "1" and direct
  198. children are included in the result.
  199. The ``path`` is relative.
  200. """
  201. raise NotImplementedError
  202. @classmethod
  203. def move(cls, item, to_collection, to_href):
  204. """Move an object.
  205. ``item`` is the item to move.
  206. ``to_collection`` is the target collection.
  207. ``to_href`` is the target name in ``to_collection``. An item with the
  208. same name might already exist.
  209. """
  210. if item.collection.path == to_collection.path and item.href == to_href:
  211. return
  212. if to_collection.has(to_href):
  213. to_collection.update(to_href, item.item)
  214. else:
  215. to_collection.upload(to_href, item.item)
  216. item.collection.delete(item.href)
  217. @property
  218. def etag(self):
  219. return get_etag(self.serialize())
  220. @classmethod
  221. def create_collection(cls, href, collection=None, props=None):
  222. """Create a collection.
  223. ``collection`` is a list of vobject components.
  224. ``props`` are metadata values for the collection.
  225. ``props["tag"]`` is the type of collection (VCALENDAR or
  226. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  227. collection.
  228. """
  229. raise NotImplementedError
  230. def list(self):
  231. """List collection items."""
  232. raise NotImplementedError
  233. def get(self, href):
  234. """Fetch a single item."""
  235. raise NotImplementedError
  236. def get_multi(self, hrefs):
  237. """Fetch multiple items. Duplicate hrefs must be ignored.
  238. Functionally similar to ``get``, but might bring performance benefits
  239. on some storages when used cleverly.
  240. """
  241. for href in set(hrefs):
  242. yield self.get(href)
  243. def pre_filtered_list(self, filters):
  244. """List collection items with optional pre filtering.
  245. This could largely improve performance of reports depending on
  246. the filters and this implementation.
  247. This returns all event by default
  248. """
  249. return [self.get(href) for href, _ in self.list()]
  250. def has(self, href):
  251. """Check if an item exists by its href.
  252. Functionally similar to ``get``, but might bring performance benefits
  253. on some storages when used cleverly.
  254. """
  255. return self.get(href) is not None
  256. def upload(self, href, vobject_item):
  257. """Upload a new item."""
  258. raise NotImplementedError
  259. def update(self, href, vobject_item, etag=None):
  260. """Update an item.
  261. Functionally similar to ``delete`` plus ``upload``, but might bring
  262. performance benefits on some storages when used cleverly.
  263. """
  264. self.delete(href, etag)
  265. self.upload(href, vobject_item)
  266. def delete(self, href=None, etag=None):
  267. """Delete an item.
  268. When ``href`` is ``None``, delete the collection.
  269. """
  270. raise NotImplementedError
  271. def get_meta(self, key):
  272. """Get metadata value for collection."""
  273. raise NotImplementedError
  274. def set_meta(self, props):
  275. """Set metadata values for collection."""
  276. raise NotImplementedError
  277. @property
  278. def last_modified(self):
  279. """Get the HTTP-datetime of when the collection was modified."""
  280. raise NotImplementedError
  281. def serialize(self):
  282. """Get the unicode string representing the whole collection."""
  283. raise NotImplementedError
  284. @classmethod
  285. @contextmanager
  286. def acquire_lock(cls, mode):
  287. """Set a context manager to lock the whole storage.
  288. ``mode`` must either be "r" for shared access or "w" for exclusive
  289. access.
  290. """
  291. raise NotImplementedError
  292. class Collection(BaseCollection):
  293. """Collection stored in several files per calendar."""
  294. def __init__(self, path, principal=False, folder=None):
  295. if not folder:
  296. folder = self._get_collection_root_folder()
  297. # Path should already be sanitized
  298. self.path = sanitize_path(path).strip("/")
  299. self.encoding = self.configuration.get("encoding", "stock")
  300. self._filesystem_path = path_to_filesystem(folder, self.path)
  301. self._props_path = os.path.join(
  302. self._filesystem_path, ".Radicale.props")
  303. split_path = self.path.split("/")
  304. self.owner = split_path[0] if len(split_path) > 1 else None
  305. self.is_principal = principal
  306. @classmethod
  307. def _get_collection_root_folder(cls):
  308. filesystem_folder = os.path.expanduser(
  309. cls.configuration.get("storage", "filesystem_folder"))
  310. return os.path.join(filesystem_folder, "collection-root")
  311. @contextmanager
  312. def _atomic_write(self, path, mode="w"):
  313. with _EncodedAtomicWriter(path, self.encoding, mode).open() as fd:
  314. yield fd
  315. def _find_available_file_name(self):
  316. # Prevent infinite loop
  317. for _ in range(10000):
  318. file_name = hex(getrandbits(32))[2:]
  319. if not self.has(file_name):
  320. return file_name
  321. raise FileExistsError(errno.EEXIST, "No usable file name found")
  322. @classmethod
  323. def discover(cls, path, depth="0"):
  324. if path is None:
  325. # Wrong URL
  326. return
  327. # Path should already be sanitized
  328. sane_path = sanitize_path(path).strip("/")
  329. attributes = sane_path.split("/")
  330. if not attributes[0]:
  331. attributes.pop()
  332. # Try to guess if the path leads to a collection or an item
  333. folder = cls._get_collection_root_folder()
  334. try:
  335. filesystem_path = path_to_filesystem(folder, sane_path)
  336. except ValueError:
  337. # Path is unsafe
  338. return
  339. if not os.path.isdir(filesystem_path):
  340. if attributes and os.path.isfile(filesystem_path):
  341. href = attributes.pop()
  342. else:
  343. return
  344. else:
  345. href = None
  346. path = "/".join(attributes)
  347. principal = len(attributes) == 1
  348. collection = cls(path, principal)
  349. if href:
  350. yield collection.get(href)
  351. return
  352. yield collection
  353. if depth == "0":
  354. return
  355. for item in collection.list():
  356. yield collection.get(item[0])
  357. for href in os.listdir(filesystem_path):
  358. if not is_safe_filesystem_path_component(href):
  359. cls.logger.debug("Skipping collection: %s", href)
  360. continue
  361. child_filesystem_path = path_to_filesystem(filesystem_path, href)
  362. if os.path.isdir(child_filesystem_path):
  363. child_principal = len(attributes) == 0
  364. yield cls(child_filesystem_path, child_principal)
  365. @classmethod
  366. def create_collection(cls, href, collection=None, props=None):
  367. folder = cls._get_collection_root_folder()
  368. # Path should already be sanitized
  369. sane_path = sanitize_path(href).strip("/")
  370. attributes = sane_path.split("/")
  371. if not attributes[0]:
  372. attributes.pop()
  373. principal = len(attributes) == 1
  374. filesystem_path = path_to_filesystem(folder, sane_path)
  375. if not props:
  376. props = {}
  377. if not props.get("tag") and collection:
  378. props["tag"] = collection[0].name
  379. if not props:
  380. os.makedirs(filesystem_path, exist_ok=True)
  381. return cls(sane_path, principal=principal)
  382. parent_dir = os.path.dirname(filesystem_path)
  383. os.makedirs(parent_dir, exist_ok=True)
  384. # Create a temporary directory with an unsafe name
  385. with TemporaryDirectory(
  386. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  387. # The temporary directory itself can't be renamed
  388. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  389. os.makedirs(tmp_filesystem_path)
  390. self = cls("/", principal=principal, folder=tmp_filesystem_path)
  391. self.set_meta(props)
  392. if collection:
  393. if props.get("tag") == "VCALENDAR":
  394. collection, = collection
  395. items = []
  396. for content in ("vevent", "vtodo", "vjournal"):
  397. items.extend(
  398. getattr(collection, "%s_list" % content, []))
  399. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  400. for uid, items in items_by_uid:
  401. new_collection = vobject.iCalendar()
  402. for item in items:
  403. new_collection.add(item)
  404. self.upload(
  405. self._find_available_file_name(), new_collection)
  406. elif props.get("tag") == "VCARD":
  407. for card in collection:
  408. self.upload(self._find_available_file_name(), card)
  409. os.rename(tmp_filesystem_path, filesystem_path)
  410. sync_directory(parent_dir)
  411. return cls(sane_path, principal=principal)
  412. def list(self):
  413. try:
  414. hrefs = os.listdir(self._filesystem_path)
  415. except IOError:
  416. return
  417. for href in hrefs:
  418. if not is_safe_filesystem_path_component(href):
  419. self.logger.debug("Skipping component: %s", href)
  420. continue
  421. path = os.path.join(self._filesystem_path, href)
  422. if os.path.isfile(path):
  423. with open(path, encoding=self.encoding) as fd:
  424. yield href, get_etag(fd.read())
  425. def get(self, href):
  426. if not href:
  427. return None
  428. href = href.strip("{}").replace("/", "_")
  429. if not is_safe_filesystem_path_component(href):
  430. self.logger.debug(
  431. "Can't translate name safely to filesystem: %s", href)
  432. return None
  433. path = path_to_filesystem(self._filesystem_path, href)
  434. if not os.path.isfile(path):
  435. return None
  436. with open(path, encoding=self.encoding) as fd:
  437. text = fd.read()
  438. last_modified = time.strftime(
  439. "%a, %d %b %Y %H:%M:%S GMT",
  440. time.gmtime(os.path.getmtime(path)))
  441. return Item(self, vobject.readOne(text), href, last_modified)
  442. def has(self, href):
  443. return self.get(href) is not None
  444. def upload(self, href, vobject_item):
  445. if not is_safe_filesystem_path_component(href):
  446. raise UnsafePathError(href)
  447. path = path_to_filesystem(self._filesystem_path, href)
  448. if os.path.exists(path):
  449. raise ComponentExistsError(href)
  450. item = Item(self, vobject_item, href)
  451. with self._atomic_write(path) as fd:
  452. fd.write(item.serialize())
  453. return item
  454. def update(self, href, vobject_item, etag=None):
  455. if not is_safe_filesystem_path_component(href):
  456. raise UnsafePathError(href)
  457. path = path_to_filesystem(self._filesystem_path, href)
  458. if not os.path.isfile(path):
  459. raise ComponentNotFoundError(href)
  460. with open(path, encoding=self.encoding) as fd:
  461. text = fd.read()
  462. if etag and etag != get_etag(text):
  463. raise EtagMismatchError(etag, get_etag(text))
  464. item = Item(self, vobject_item, href)
  465. with self._atomic_write(path) as fd:
  466. fd.write(item.serialize())
  467. return item
  468. def delete(self, href=None, etag=None):
  469. if href is None:
  470. # Delete the collection
  471. if os.path.isdir(self._filesystem_path):
  472. shutil.rmtree(self._filesystem_path)
  473. else:
  474. # Delete an item
  475. if not is_safe_filesystem_path_component(href):
  476. raise UnsafePathError(href)
  477. path = path_to_filesystem(self._filesystem_path, href)
  478. if not os.path.isfile(path):
  479. raise ComponentNotFoundError(href)
  480. with open(path, encoding=self.encoding) as fd:
  481. text = fd.read()
  482. if etag and etag != get_etag(text):
  483. raise EtagMismatchError(etag, get_etag(text))
  484. os.remove(path)
  485. def get_meta(self, key):
  486. if os.path.exists(self._props_path):
  487. with open(self._props_path, encoding=self.encoding) as prop:
  488. return json.load(prop).get(key)
  489. def set_meta(self, props):
  490. if os.path.exists(self._props_path):
  491. with open(self._props_path, encoding=self.encoding) as prop:
  492. old_props = json.load(prop)
  493. old_props.update(props)
  494. props = old_props
  495. props = {key: value for key, value in props.items() if value}
  496. with self._atomic_write(self._props_path, "w+") as prop:
  497. json.dump(props, prop)
  498. @property
  499. def last_modified(self):
  500. last = max([os.path.getmtime(self._filesystem_path)] + [
  501. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  502. for filename in os.listdir(self._filesystem_path)] or [0])
  503. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  504. def serialize(self):
  505. if not os.path.exists(self._filesystem_path):
  506. return None
  507. items = []
  508. for href in os.listdir(self._filesystem_path):
  509. if not is_safe_filesystem_path_component(href):
  510. self.logger.debug("Skipping component: %s", href)
  511. continue
  512. path = os.path.join(self._filesystem_path, href)
  513. if os.path.isfile(path):
  514. with open(path, encoding=self.encoding) as fd:
  515. items.append(vobject.readOne(fd.read()))
  516. if self.get_meta("tag") == "VCALENDAR":
  517. collection = vobject.iCalendar()
  518. for item in items:
  519. for content in ("vevent", "vtodo", "vjournal"):
  520. if content in item.contents:
  521. for item_part in getattr(item, "%s_list" % content):
  522. collection.add(item_part)
  523. break
  524. return collection.serialize()
  525. elif self.get_meta("tag") == "VADDRESSBOOK":
  526. return "".join([item.serialize() for item in items])
  527. return ""
  528. _lock = threading.Lock()
  529. _waiters = []
  530. _lock_file = None
  531. _lock_file_locked = False
  532. _readers = 0
  533. _writer = False
  534. @classmethod
  535. @contextmanager
  536. def acquire_lock(cls, mode):
  537. def condition():
  538. if mode == "r":
  539. return not cls._writer
  540. else:
  541. return not cls._writer and cls._readers == 0
  542. # Use a primitive lock which only works within one process as a
  543. # precondition for inter-process file-based locking
  544. with cls._lock:
  545. if cls._waiters or not condition():
  546. # Use FIFO for access requests
  547. waiter = threading.Condition(lock=cls._lock)
  548. cls._waiters.append(waiter)
  549. while True:
  550. waiter.wait()
  551. if condition():
  552. break
  553. cls._waiters.pop(0)
  554. if mode == "r":
  555. cls._readers += 1
  556. # Notify additional potential readers
  557. if cls._waiters:
  558. cls._waiters[0].notify()
  559. else:
  560. cls._writer = True
  561. if not cls._lock_file:
  562. folder = os.path.expanduser(
  563. cls.configuration.get("storage", "filesystem_folder"))
  564. if not os.path.exists(folder):
  565. os.makedirs(folder, exist_ok=True)
  566. lock_path = os.path.join(folder, ".Radicale.lock")
  567. cls._lock_file = open(lock_path, "w+")
  568. # Set access rights to a necessary minimum to prevent locking
  569. # by arbitrary users
  570. try:
  571. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  572. except OSError:
  573. cls.logger.debug("Failed to set permissions on lock file")
  574. if not cls._lock_file_locked:
  575. if os.name == "nt":
  576. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  577. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  578. overlapped = Overlapped()
  579. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  580. cls.logger.debug("Locking not supported")
  581. elif os.name == "posix":
  582. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  583. try:
  584. fcntl.flock(cls._lock_file.fileno(), _cmd)
  585. except OSError:
  586. cls.logger.debug("Locking not supported")
  587. cls._lock_file_locked = True
  588. try:
  589. yield
  590. finally:
  591. with cls._lock:
  592. if mode == "r":
  593. cls._readers -= 1
  594. else:
  595. cls._writer = False
  596. if cls._readers == 0:
  597. if os.name == "nt":
  598. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  599. overlapped = Overlapped()
  600. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  601. cls.logger.debug("Unlocking not supported")
  602. elif os.name == "posix":
  603. try:
  604. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  605. except OSError:
  606. cls.logger.debug("Unlocking not supported")
  607. cls._lock_file_locked = False
  608. if cls._waiters:
  609. cls._waiters[0].notify()