storage.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. @property
  203. def etag(self):
  204. return get_etag(self.serialize())
  205. @classmethod
  206. def create_collection(cls, href, collection=None, props=None):
  207. """Create a collection.
  208. ``collection`` is a list of vobject components.
  209. ``props`` are metadata values for the collection.
  210. ``props["tag"]`` is the type of collection (VCALENDAR or
  211. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  212. collection.
  213. """
  214. raise NotImplementedError
  215. def list(self):
  216. """List collection items."""
  217. raise NotImplementedError
  218. def get(self, href):
  219. """Fetch a single item."""
  220. raise NotImplementedError
  221. def get_multi(self, hrefs):
  222. """Fetch multiple items. Duplicate hrefs must be ignored.
  223. Functionally similar to ``get``, but might bring performance benefits
  224. on some storages when used cleverly.
  225. """
  226. for href in set(hrefs):
  227. yield self.get(href)
  228. def pre_filtered_list(self, filters):
  229. """List collection items with optional pre filtering.
  230. This could largely improve performance of reports depending on
  231. the filters and this implementation.
  232. This returns all event by default
  233. """
  234. return [self.get(href) for href, _ in self.list()]
  235. def has(self, href):
  236. """Check if an item exists by its href.
  237. Functionally similar to ``get``, but might bring performance benefits
  238. on some storages when used cleverly.
  239. """
  240. return self.get(href) is not None
  241. def upload(self, href, vobject_item):
  242. """Upload a new item."""
  243. raise NotImplementedError
  244. def update(self, href, vobject_item, etag=None):
  245. """Update an item.
  246. Functionally similar to ``delete`` plus ``upload``, but might bring
  247. performance benefits on some storages when used cleverly.
  248. """
  249. self.delete(href, etag)
  250. self.upload(href, vobject_item)
  251. def delete(self, href=None, etag=None):
  252. """Delete an item.
  253. When ``href`` is ``None``, delete the collection.
  254. """
  255. raise NotImplementedError
  256. def get_meta(self, key):
  257. """Get metadata value for collection."""
  258. raise NotImplementedError
  259. def set_meta(self, props):
  260. """Set metadata values for collection."""
  261. raise NotImplementedError
  262. @property
  263. def last_modified(self):
  264. """Get the HTTP-datetime of when the collection was modified."""
  265. raise NotImplementedError
  266. def serialize(self):
  267. """Get the unicode string representing the whole collection."""
  268. raise NotImplementedError
  269. @classmethod
  270. @contextmanager
  271. def acquire_lock(cls, mode):
  272. """Set a context manager to lock the whole storage.
  273. ``mode`` must either be "r" for shared access or "w" for exclusive
  274. access.
  275. """
  276. raise NotImplementedError
  277. class Collection(BaseCollection):
  278. """Collection stored in several files per calendar."""
  279. def __init__(self, path, principal=False, folder=None):
  280. if not folder:
  281. folder = self._get_collection_root_folder()
  282. # Path should already be sanitized
  283. self.path = sanitize_path(path).strip("/")
  284. self.encoding = self.configuration.get("encoding", "stock")
  285. self._filesystem_path = path_to_filesystem(folder, self.path)
  286. self._props_path = os.path.join(
  287. self._filesystem_path, ".Radicale.props")
  288. split_path = self.path.split("/")
  289. self.owner = split_path[0] if len(split_path) > 1 else None
  290. self.is_principal = principal
  291. @classmethod
  292. def _get_collection_root_folder(cls):
  293. filesystem_folder = os.path.expanduser(
  294. cls.configuration.get("storage", "filesystem_folder"))
  295. return os.path.join(filesystem_folder, "collection-root")
  296. @contextmanager
  297. def _atomic_write(self, path, mode="w"):
  298. with _EncodedAtomicWriter(path, self.encoding, mode).open() as fd:
  299. yield fd
  300. def _find_available_file_name(self):
  301. # Prevent infinite loop
  302. for _ in range(10000):
  303. file_name = hex(getrandbits(32))[2:]
  304. if not self.has(file_name):
  305. return file_name
  306. raise FileExistsError(errno.EEXIST, "No usable file name found")
  307. @classmethod
  308. def _makedirs_synced(cls, filesystem_path, exist_ok=False):
  309. if os.path.isdir(filesystem_path) and exist_ok:
  310. return
  311. parent_filesystem_path = os.path.dirname(filesystem_path)
  312. # Prevent infinite loop
  313. if filesystem_path != parent_filesystem_path:
  314. # Create parent dirs recursively
  315. cls._makedirs_synced(parent_filesystem_path, exist_ok=True)
  316. # Possible race!
  317. os.makedirs(filesystem_path, exist_ok=exist_ok)
  318. sync_directory(parent_filesystem_path)
  319. @classmethod
  320. def discover(cls, path, depth="0"):
  321. if path is None:
  322. # Wrong URL
  323. return
  324. # Path should already be sanitized
  325. sane_path = sanitize_path(path).strip("/")
  326. attributes = sane_path.split("/")
  327. if not attributes[0]:
  328. attributes.pop()
  329. # Try to guess if the path leads to a collection or an item
  330. folder = cls._get_collection_root_folder()
  331. try:
  332. filesystem_path = path_to_filesystem(folder, sane_path)
  333. except ValueError:
  334. # Path is unsafe
  335. return
  336. if not os.path.isdir(filesystem_path):
  337. if attributes and os.path.isfile(filesystem_path):
  338. href = attributes.pop()
  339. else:
  340. return
  341. else:
  342. href = None
  343. path = "/".join(attributes)
  344. principal = len(attributes) == 1
  345. collection = cls(path, principal)
  346. if href:
  347. yield collection.get(href)
  348. return
  349. yield collection
  350. if depth == "0":
  351. return
  352. for item in collection.list():
  353. yield collection.get(item[0])
  354. for href in os.listdir(filesystem_path):
  355. if not is_safe_filesystem_path_component(href):
  356. cls.logger.debug("Skipping collection: %s", href)
  357. continue
  358. child_filesystem_path = path_to_filesystem(filesystem_path, href)
  359. if os.path.isdir(child_filesystem_path):
  360. child_principal = len(attributes) == 0
  361. yield cls(child_filesystem_path, child_principal)
  362. @classmethod
  363. def create_collection(cls, href, collection=None, props=None):
  364. folder = cls._get_collection_root_folder()
  365. # Path should already be sanitized
  366. sane_path = sanitize_path(href).strip("/")
  367. attributes = sane_path.split("/")
  368. if not attributes[0]:
  369. attributes.pop()
  370. principal = len(attributes) == 1
  371. filesystem_path = path_to_filesystem(folder, sane_path)
  372. if not props:
  373. props = {}
  374. if not props.get("tag") and collection:
  375. props["tag"] = collection[0].name
  376. if not props:
  377. cls._makedirs_synced(filesystem_path, exist_ok=True)
  378. return cls(sane_path, principal=principal)
  379. parent_dir = os.path.dirname(filesystem_path)
  380. cls._makedirs_synced(parent_dir, exist_ok=True)
  381. # Create a temporary directory with an unsafe name
  382. with TemporaryDirectory(
  383. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  384. # The temporary directory itself can't be renamed
  385. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  386. os.makedirs(tmp_filesystem_path)
  387. self = cls("/", principal=principal, folder=tmp_filesystem_path)
  388. self.set_meta(props)
  389. if collection:
  390. if props.get("tag") == "VCALENDAR":
  391. collection, = collection
  392. items = []
  393. for content in ("vevent", "vtodo", "vjournal"):
  394. items.extend(
  395. getattr(collection, "%s_list" % content, []))
  396. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  397. for uid, items in items_by_uid:
  398. new_collection = vobject.iCalendar()
  399. for item in items:
  400. new_collection.add(item)
  401. self.upload(
  402. self._find_available_file_name(), new_collection)
  403. elif props.get("tag") == "VCARD":
  404. for card in collection:
  405. self.upload(self._find_available_file_name(), card)
  406. os.rename(tmp_filesystem_path, filesystem_path)
  407. sync_directory(parent_dir)
  408. return cls(sane_path, principal=principal)
  409. def list(self):
  410. try:
  411. hrefs = os.listdir(self._filesystem_path)
  412. except IOError:
  413. return
  414. for href in hrefs:
  415. if not is_safe_filesystem_path_component(href):
  416. self.logger.debug("Skipping component: %s", href)
  417. continue
  418. path = os.path.join(self._filesystem_path, href)
  419. if os.path.isfile(path):
  420. with open(path, encoding=self.encoding) as fd:
  421. yield href, get_etag(fd.read())
  422. def get(self, href):
  423. if not href:
  424. return None
  425. href = href.strip("{}").replace("/", "_")
  426. if not is_safe_filesystem_path_component(href):
  427. self.logger.debug(
  428. "Can't translate name safely to filesystem: %s", href)
  429. return None
  430. path = path_to_filesystem(self._filesystem_path, href)
  431. if not os.path.isfile(path):
  432. return None
  433. with open(path, encoding=self.encoding) as fd:
  434. text = fd.read()
  435. last_modified = time.strftime(
  436. "%a, %d %b %Y %H:%M:%S GMT",
  437. time.gmtime(os.path.getmtime(path)))
  438. return Item(self, vobject.readOne(text), href, last_modified)
  439. def has(self, href):
  440. return self.get(href) is not None
  441. def upload(self, href, vobject_item):
  442. if not is_safe_filesystem_path_component(href):
  443. raise UnsafePathError(href)
  444. path = path_to_filesystem(self._filesystem_path, href)
  445. if os.path.exists(path):
  446. raise ComponentExistsError(href)
  447. item = Item(self, vobject_item, href)
  448. with self._atomic_write(path) as fd:
  449. fd.write(item.serialize())
  450. return item
  451. def update(self, href, vobject_item, etag=None):
  452. if not is_safe_filesystem_path_component(href):
  453. raise UnsafePathError(href)
  454. path = path_to_filesystem(self._filesystem_path, href)
  455. if not os.path.isfile(path):
  456. raise ComponentNotFoundError(href)
  457. with open(path, encoding=self.encoding) as fd:
  458. text = fd.read()
  459. if etag and etag != get_etag(text):
  460. raise EtagMismatchError(etag, get_etag(text))
  461. item = Item(self, vobject_item, href)
  462. with self._atomic_write(path) as fd:
  463. fd.write(item.serialize())
  464. return item
  465. def delete(self, href=None, etag=None):
  466. if href is None:
  467. # Delete the collection
  468. if os.path.isdir(self._filesystem_path):
  469. shutil.rmtree(self._filesystem_path)
  470. else:
  471. # Delete an item
  472. if not is_safe_filesystem_path_component(href):
  473. raise UnsafePathError(href)
  474. path = path_to_filesystem(self._filesystem_path, href)
  475. if not os.path.isfile(path):
  476. raise ComponentNotFoundError(href)
  477. with open(path, encoding=self.encoding) as fd:
  478. text = fd.read()
  479. if etag and etag != get_etag(text):
  480. raise EtagMismatchError(etag, get_etag(text))
  481. os.remove(path)
  482. def get_meta(self, key):
  483. if os.path.exists(self._props_path):
  484. with open(self._props_path, encoding=self.encoding) as prop:
  485. return json.load(prop).get(key)
  486. def set_meta(self, props):
  487. if os.path.exists(self._props_path):
  488. with open(self._props_path, encoding=self.encoding) as prop:
  489. old_props = json.load(prop)
  490. old_props.update(props)
  491. props = old_props
  492. props = {key: value for key, value in props.items() if value}
  493. with self._atomic_write(self._props_path, "w+") as prop:
  494. json.dump(props, prop)
  495. @property
  496. def last_modified(self):
  497. last = max([os.path.getmtime(self._filesystem_path)] + [
  498. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  499. for filename in os.listdir(self._filesystem_path)] or [0])
  500. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  501. def serialize(self):
  502. if not os.path.exists(self._filesystem_path):
  503. return None
  504. items = []
  505. for href in os.listdir(self._filesystem_path):
  506. if not is_safe_filesystem_path_component(href):
  507. self.logger.debug("Skipping component: %s", href)
  508. continue
  509. path = os.path.join(self._filesystem_path, href)
  510. if os.path.isfile(path):
  511. with open(path, encoding=self.encoding) as fd:
  512. items.append(vobject.readOne(fd.read()))
  513. if self.get_meta("tag") == "VCALENDAR":
  514. collection = vobject.iCalendar()
  515. for item in items:
  516. for content in ("vevent", "vtodo", "vjournal"):
  517. if content in item.contents:
  518. for item_part in getattr(item, "%s_list" % content):
  519. collection.add(item_part)
  520. break
  521. return collection.serialize()
  522. elif self.get_meta("tag") == "VADDRESSBOOK":
  523. return "".join([item.serialize() for item in items])
  524. return ""
  525. _lock = threading.Lock()
  526. _waiters = []
  527. _lock_file = None
  528. _lock_file_locked = False
  529. _readers = 0
  530. _writer = False
  531. @classmethod
  532. @contextmanager
  533. def acquire_lock(cls, mode):
  534. def condition():
  535. if mode == "r":
  536. return not cls._writer
  537. else:
  538. return not cls._writer and cls._readers == 0
  539. # Use a primitive lock which only works within one process as a
  540. # precondition for inter-process file-based locking
  541. with cls._lock:
  542. if cls._waiters or not condition():
  543. # Use FIFO for access requests
  544. waiter = threading.Condition(lock=cls._lock)
  545. cls._waiters.append(waiter)
  546. while True:
  547. waiter.wait()
  548. if condition():
  549. break
  550. cls._waiters.pop(0)
  551. if mode == "r":
  552. cls._readers += 1
  553. # Notify additional potential readers
  554. if cls._waiters:
  555. cls._waiters[0].notify()
  556. else:
  557. cls._writer = True
  558. if not cls._lock_file:
  559. folder = os.path.expanduser(
  560. cls.configuration.get("storage", "filesystem_folder"))
  561. cls._makedirs_synced(folder, exist_ok=True)
  562. lock_path = os.path.join(folder, ".Radicale.lock")
  563. cls._lock_file = open(lock_path, "w+")
  564. # Set access rights to a necessary minimum to prevent locking
  565. # by arbitrary users
  566. try:
  567. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  568. except OSError:
  569. cls.logger.debug("Failed to set permissions on lock file")
  570. if not cls._lock_file_locked:
  571. if os.name == "nt":
  572. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  573. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  574. overlapped = Overlapped()
  575. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  576. cls.logger.debug("Locking not supported")
  577. elif os.name == "posix":
  578. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  579. try:
  580. fcntl.flock(cls._lock_file.fileno(), _cmd)
  581. except OSError:
  582. cls.logger.debug("Locking not supported")
  583. cls._lock_file_locked = True
  584. try:
  585. yield
  586. finally:
  587. with cls._lock:
  588. if mode == "r":
  589. cls._readers -= 1
  590. else:
  591. cls._writer = False
  592. if cls._readers == 0:
  593. if os.name == "nt":
  594. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  595. overlapped = Overlapped()
  596. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  597. cls.logger.debug("Unlocking not supported")
  598. elif os.name == "posix":
  599. try:
  600. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  601. except OSError:
  602. cls.logger.debug("Unlocking not supported")
  603. cls._lock_file_locked = False
  604. if cls._waiters:
  605. cls._waiters[0].notify()