storage.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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. The root collection "/" must always exist.
  201. """
  202. raise NotImplementedError
  203. @property
  204. def etag(self):
  205. return get_etag(self.serialize())
  206. @classmethod
  207. def create_collection(cls, href, collection=None, props=None):
  208. """Create a collection.
  209. ``collection`` is a list of vobject components.
  210. ``props`` are metadata values for the collection.
  211. ``props["tag"]`` is the type of collection (VCALENDAR or
  212. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  213. collection.
  214. """
  215. raise NotImplementedError
  216. def list(self):
  217. """List collection items."""
  218. raise NotImplementedError
  219. def get(self, href):
  220. """Fetch a single item."""
  221. raise NotImplementedError
  222. def get_multi(self, hrefs):
  223. """Fetch multiple items. Duplicate hrefs must be ignored.
  224. Functionally similar to ``get``, but might bring performance benefits
  225. on some storages when used cleverly.
  226. """
  227. for href in set(hrefs):
  228. yield self.get(href)
  229. def pre_filtered_list(self, filters):
  230. """List collection items with optional pre filtering.
  231. This could largely improve performance of reports depending on
  232. the filters and this implementation.
  233. This returns all event by default
  234. """
  235. return [self.get(href) for href, _ in self.list()]
  236. def has(self, href):
  237. """Check if an item exists by its href.
  238. Functionally similar to ``get``, but might bring performance benefits
  239. on some storages when used cleverly.
  240. """
  241. return self.get(href) is not None
  242. def upload(self, href, vobject_item):
  243. """Upload a new item."""
  244. raise NotImplementedError
  245. def update(self, href, vobject_item, etag=None):
  246. """Update an item.
  247. Functionally similar to ``delete`` plus ``upload``, but might bring
  248. performance benefits on some storages when used cleverly.
  249. """
  250. self.delete(href, etag)
  251. self.upload(href, vobject_item)
  252. def delete(self, href=None, etag=None):
  253. """Delete an item.
  254. When ``href`` is ``None``, delete the collection.
  255. """
  256. raise NotImplementedError
  257. def get_meta(self, key):
  258. """Get metadata value for collection."""
  259. raise NotImplementedError
  260. def set_meta(self, props):
  261. """Set metadata values for collection."""
  262. raise NotImplementedError
  263. @property
  264. def last_modified(self):
  265. """Get the HTTP-datetime of when the collection was modified."""
  266. raise NotImplementedError
  267. def serialize(self):
  268. """Get the unicode string representing the whole collection."""
  269. raise NotImplementedError
  270. @classmethod
  271. @contextmanager
  272. def acquire_lock(cls, mode):
  273. """Set a context manager to lock the whole storage.
  274. ``mode`` must either be "r" for shared access or "w" for exclusive
  275. access.
  276. """
  277. raise NotImplementedError
  278. class Collection(BaseCollection):
  279. """Collection stored in several files per calendar."""
  280. def __init__(self, path, principal=False, folder=None):
  281. if not folder:
  282. folder = self._get_collection_root_folder()
  283. # Path should already be sanitized
  284. self.path = sanitize_path(path).strip("/")
  285. self.encoding = self.configuration.get("encoding", "stock")
  286. self._filesystem_path = path_to_filesystem(folder, self.path)
  287. self._props_path = os.path.join(
  288. self._filesystem_path, ".Radicale.props")
  289. split_path = self.path.split("/")
  290. self.owner = split_path[0] if len(split_path) > 1 else None
  291. self.is_principal = principal
  292. @classmethod
  293. def _get_collection_root_folder(cls):
  294. filesystem_folder = os.path.expanduser(
  295. cls.configuration.get("storage", "filesystem_folder"))
  296. return os.path.join(filesystem_folder, "collection-root")
  297. @contextmanager
  298. def _atomic_write(self, path, mode="w"):
  299. with _EncodedAtomicWriter(path, self.encoding, mode).open() as fd:
  300. yield fd
  301. def _find_available_file_name(self):
  302. # Prevent infinite loop
  303. for _ in range(10000):
  304. file_name = hex(getrandbits(32))[2:]
  305. if not self.has(file_name):
  306. return file_name
  307. raise FileExistsError(errno.EEXIST, "No usable file name found")
  308. @classmethod
  309. def _makedirs_synced(cls, filesystem_path, exist_ok=False):
  310. if os.path.isdir(filesystem_path) and exist_ok:
  311. return
  312. parent_filesystem_path = os.path.dirname(filesystem_path)
  313. # Prevent infinite loop
  314. if filesystem_path != parent_filesystem_path:
  315. # Create parent dirs recursively
  316. cls._makedirs_synced(parent_filesystem_path, exist_ok=True)
  317. # Possible race!
  318. os.makedirs(filesystem_path, exist_ok=exist_ok)
  319. sync_directory(parent_filesystem_path)
  320. @classmethod
  321. def discover(cls, path, depth="0"):
  322. if path is None:
  323. # Wrong URL
  324. return
  325. # Path should already be sanitized
  326. sane_path = sanitize_path(path).strip("/")
  327. attributes = sane_path.split("/")
  328. if not attributes[0]:
  329. attributes.pop()
  330. # Try to guess if the path leads to a collection or an item
  331. folder = cls._get_collection_root_folder()
  332. # Create the root collection
  333. cls._makedirs_synced(folder, exist_ok=True)
  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. cls._makedirs_synced(filesystem_path, exist_ok=True)
  381. return cls(sane_path, principal=principal)
  382. parent_dir = os.path.dirname(filesystem_path)
  383. cls._makedirs_synced(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. cls._makedirs_synced(folder, exist_ok=True)
  565. lock_path = os.path.join(folder, ".Radicale.lock")
  566. cls._lock_file = open(lock_path, "w+")
  567. # Set access rights to a necessary minimum to prevent locking
  568. # by arbitrary users
  569. try:
  570. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  571. except OSError:
  572. cls.logger.debug("Failed to set permissions on lock file")
  573. if not cls._lock_file_locked:
  574. if os.name == "nt":
  575. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  576. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  577. overlapped = Overlapped()
  578. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  579. cls.logger.debug("Locking not supported")
  580. elif os.name == "posix":
  581. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  582. try:
  583. fcntl.flock(cls._lock_file.fileno(), _cmd)
  584. except OSError:
  585. cls.logger.debug("Locking not supported")
  586. cls._lock_file_locked = True
  587. try:
  588. yield
  589. finally:
  590. with cls._lock:
  591. if mode == "r":
  592. cls._readers -= 1
  593. else:
  594. cls._writer = False
  595. if cls._readers == 0:
  596. if os.name == "nt":
  597. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  598. overlapped = Overlapped()
  599. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  600. cls.logger.debug("Unlocking not supported")
  601. elif os.name == "posix":
  602. try:
  603. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  604. except OSError:
  605. cls.logger.debug("Unlocking not supported")
  606. cls._lock_file_locked = False
  607. if cls._waiters:
  608. cls._waiters[0].notify()