storage.py 25 KB

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