storage.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 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 binascii
  24. import contextlib
  25. import json
  26. import os
  27. import pickle
  28. import posixpath
  29. import shlex
  30. import subprocess
  31. import sys
  32. import threading
  33. import time
  34. from contextlib import contextmanager
  35. from hashlib import md5
  36. from importlib import import_module
  37. from itertools import chain, groupby
  38. from random import getrandbits
  39. from tempfile import NamedTemporaryFile, TemporaryDirectory
  40. import pkg_resources
  41. import vobject
  42. if sys.version_info >= (3, 5):
  43. # HACK: Avoid import cycle for Python < 3.5
  44. from . import xmlutils
  45. if os.name == "nt":
  46. import ctypes
  47. import ctypes.wintypes
  48. import msvcrt
  49. LOCKFILE_EXCLUSIVE_LOCK = 2
  50. if ctypes.sizeof(ctypes.c_void_p) == 4:
  51. ULONG_PTR = ctypes.c_uint32
  52. else:
  53. ULONG_PTR = ctypes.c_uint64
  54. class Overlapped(ctypes.Structure):
  55. _fields_ = [
  56. ("internal", ULONG_PTR),
  57. ("internal_high", ULONG_PTR),
  58. ("offset", ctypes.wintypes.DWORD),
  59. ("offset_high", ctypes.wintypes.DWORD),
  60. ("h_event", ctypes.wintypes.HANDLE)]
  61. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  62. lock_file_ex.argtypes = [
  63. ctypes.wintypes.HANDLE,
  64. ctypes.wintypes.DWORD,
  65. ctypes.wintypes.DWORD,
  66. ctypes.wintypes.DWORD,
  67. ctypes.wintypes.DWORD,
  68. ctypes.POINTER(Overlapped)]
  69. lock_file_ex.restype = ctypes.wintypes.BOOL
  70. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  71. unlock_file_ex.argtypes = [
  72. ctypes.wintypes.HANDLE,
  73. ctypes.wintypes.DWORD,
  74. ctypes.wintypes.DWORD,
  75. ctypes.wintypes.DWORD,
  76. ctypes.POINTER(Overlapped)]
  77. unlock_file_ex.restype = ctypes.wintypes.BOOL
  78. elif os.name == "posix":
  79. import fcntl
  80. INTERNAL_TYPES = ("multifilesystem",)
  81. def load(configuration, logger):
  82. """Load the storage manager chosen in configuration."""
  83. if sys.version_info < (3, 5):
  84. # HACK: Avoid import cycle for Python < 3.5
  85. global xmlutils
  86. from . import xmlutils
  87. storage_type = configuration.get("storage", "type")
  88. if storage_type == "multifilesystem":
  89. collection_class = Collection
  90. else:
  91. try:
  92. collection_class = import_module(storage_type).Collection
  93. except Exception as e:
  94. raise RuntimeError("Failed to load storage module %r: %s" %
  95. (storage_type, e)) from e
  96. logger.info("Storage type is %r", storage_type)
  97. class CollectionCopy(collection_class):
  98. """Collection copy, avoids overriding the original class attributes."""
  99. CollectionCopy.configuration = configuration
  100. CollectionCopy.logger = logger
  101. return CollectionCopy
  102. def check_item(vobject_item):
  103. """Check vobject items for common errors."""
  104. if vobject_item.name == "VCALENDAR":
  105. for component in vobject_item.components():
  106. if component.name not in ("VTODO", "VEVENT", "VJOURNAL"):
  107. continue
  108. if not get_uid(component):
  109. raise ValueError("UID in %s is missing" % component.name)
  110. # vobject interprets recurrence rules on demand
  111. try:
  112. component.rruleset
  113. except Exception as e:
  114. raise ValueError("invalid recurrence rules in %s" %
  115. component.name) from e
  116. elif vobject_item.name == "VCARD":
  117. if not get_uid(vobject_item):
  118. raise ValueError("UID in VCARD is missing")
  119. else:
  120. raise ValueError("Unknown item type: %r" % vobject_item.name)
  121. def scandir(path, only_dirs=False, only_files=False):
  122. """Iterator for directory elements. (For compatibility with Python < 3.5)
  123. ``only_dirs`` only return directories
  124. ``only_files`` only return files
  125. """
  126. if sys.version_info >= (3, 5):
  127. for entry in os.scandir(path):
  128. if ((not only_files or entry.is_file()) and
  129. (not only_dirs or entry.is_dir())):
  130. yield entry.name
  131. else:
  132. for name in os.listdir(path):
  133. p = os.path.join(path, name)
  134. if ((not only_files or os.path.isfile(p)) and
  135. (not only_dirs or os.path.isdir(p))):
  136. yield name
  137. def get_etag(text):
  138. """Etag from collection or item.
  139. Encoded as quoted-string (see RFC 2616).
  140. """
  141. etag = md5()
  142. etag.update(text.encode("utf-8"))
  143. return '"%s"' % etag.hexdigest()
  144. def get_uid(item):
  145. """UID value of an item if defined."""
  146. return (hasattr(item, "uid") or None) and item.uid.value
  147. def sanitize_path(path):
  148. """Make path absolute with leading slash to prevent access to other data.
  149. Preserve a potential trailing slash.
  150. """
  151. trailing_slash = "/" if path.endswith("/") else ""
  152. path = posixpath.normpath(path)
  153. new_path = "/"
  154. for part in path.split("/"):
  155. if not is_safe_path_component(part):
  156. continue
  157. new_path = posixpath.join(new_path, part)
  158. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  159. return new_path + trailing_slash
  160. def is_safe_path_component(path):
  161. """Check if path is a single component of a path.
  162. Check that the path is safe to join too.
  163. """
  164. return path and "/" not in path and path not in (".", "..")
  165. def is_safe_filesystem_path_component(path):
  166. """Check if path is a single component of a local and posix filesystem
  167. path.
  168. Check that the path is safe to join too.
  169. """
  170. return (
  171. path and not os.path.splitdrive(path)[0] and
  172. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  173. not path.startswith(".") and not path.endswith("~") and
  174. is_safe_path_component(path))
  175. def path_to_filesystem(root, *paths):
  176. """Convert path to a local filesystem path relative to base_folder.
  177. `root` must be a secure filesystem path, it will be prepend to the path.
  178. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  179. """
  180. paths = [sanitize_path(path).strip("/") for path in paths]
  181. safe_path = root
  182. for path in paths:
  183. if not path:
  184. continue
  185. for part in path.split("/"):
  186. if not is_safe_filesystem_path_component(part):
  187. raise UnsafePathError(part)
  188. safe_path_parent = safe_path
  189. safe_path = os.path.join(safe_path, part)
  190. # Check for conflicting files (e.g. case-insensitive file systems
  191. # or short names on Windows file systems)
  192. if (os.path.lexists(safe_path) and
  193. part not in scandir(safe_path_parent)):
  194. raise CollidingPathError(part)
  195. return safe_path
  196. class UnsafePathError(ValueError):
  197. def __init__(self, path):
  198. message = "Can't translate name safely to filesystem: %r" % path
  199. super().__init__(message)
  200. class CollidingPathError(ValueError):
  201. def __init__(self, path):
  202. message = "File name collision: %r" % path
  203. super().__init__(message)
  204. class ComponentExistsError(ValueError):
  205. def __init__(self, path):
  206. message = "Component already exists: %r" % path
  207. super().__init__(message)
  208. class ComponentNotFoundError(ValueError):
  209. def __init__(self, path):
  210. message = "Component doesn't exist: %r" % path
  211. super().__init__(message)
  212. class Item:
  213. def __init__(self, collection, item=None, href=None, last_modified=None,
  214. text=None, etag=None):
  215. """Initialize an item.
  216. ``collection`` the parent collection.
  217. ``href`` the href of the item.
  218. ``last_modified`` the HTTP-datetime of when the item was modified.
  219. ``text`` the text representation of the item (optional if ``item`` is
  220. set).
  221. ``item`` the vobject item (optional if ``text`` is set).
  222. ``etag`` the etag of the item (optional). See ``get_etag``.
  223. """
  224. if text is None and item is None:
  225. raise ValueError("at least one of 'text' or 'item' must be set")
  226. self.collection = collection
  227. self.href = href
  228. self.last_modified = last_modified
  229. self._text = text
  230. self._item = item
  231. self._etag = etag
  232. def __getattr__(self, attr):
  233. return getattr(self.item, attr)
  234. def serialize(self):
  235. if self._text is None:
  236. self._text = self.item.serialize()
  237. return self._text
  238. @property
  239. def item(self):
  240. if self._item is None:
  241. try:
  242. self._item = vobject.readOne(self._text)
  243. except Exception as e:
  244. raise RuntimeError("Failed to parse item %r from %r: %s" %
  245. (self.href, self.collection.path, e)) from e
  246. return self._item
  247. @property
  248. def etag(self):
  249. """Encoded as quoted-string (see RFC 2616)."""
  250. if self._etag is None:
  251. self._etag = get_etag(self.serialize())
  252. return self._etag
  253. class BaseCollection:
  254. # Overriden on copy by the "load" function
  255. configuration = None
  256. logger = None
  257. # Properties of instance
  258. """The sanitized path of the collection without leading or trailing ``/``.
  259. """
  260. path = ""
  261. """The owner of the collection. (``path.split("/", maxsplit=1)[0]``)"""
  262. owner = ""
  263. """Collection is a principal. (``bool(path) and "/" not in path``)"""
  264. is_principal = False
  265. @classmethod
  266. def discover(cls, path, depth="0"):
  267. """Discover a list of collections under the given ``path``.
  268. ``path`` is sanitized.
  269. If ``depth`` is "0", only the actual object under ``path`` is
  270. returned.
  271. If ``depth`` is anything but "0", it is considered as "1" and direct
  272. children are included in the result.
  273. The root collection "/" must always exist.
  274. """
  275. raise NotImplementedError
  276. @classmethod
  277. def move(cls, item, to_collection, to_href):
  278. """Move an object.
  279. ``item`` is the item to move.
  280. ``to_collection`` is the target collection.
  281. ``to_href`` is the target name in ``to_collection``. An item with the
  282. same name might already exist.
  283. """
  284. if item.collection.path == to_collection.path and item.href == to_href:
  285. return
  286. to_collection.upload(to_href, item.item)
  287. item.collection.delete(item.href)
  288. @property
  289. def etag(self):
  290. """Encoded as quoted-string (see RFC 2616)."""
  291. return get_etag(self.serialize())
  292. @classmethod
  293. def create_collection(cls, href, collection=None, props=None):
  294. """Create a collection.
  295. ``href`` is the sanitized path.
  296. If the collection already exists and neither ``collection`` nor
  297. ``props`` are set, this method shouldn't do anything. Otherwise the
  298. existing collection must be replaced.
  299. ``collection`` is a list of vobject components.
  300. ``props`` are metadata values for the collection.
  301. ``props["tag"]`` is the type of collection (VCALENDAR or
  302. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  303. collection.
  304. """
  305. raise NotImplementedError
  306. def sync(self, old_token=None):
  307. """Get the current sync token and changed items for synchronization.
  308. ``old_token`` an old sync token which is used as the base of the
  309. delta update. If sync token is missing, all items are returned.
  310. ValueError is raised for invalid or old tokens.
  311. WARNING: This simple default implementation treats all sync-token as
  312. invalid. It adheres to the specification but some clients
  313. (e.g. InfCloud) don't like it. Subclasses should provide a
  314. more sophisticated implementation.
  315. """
  316. token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"")
  317. if old_token:
  318. raise ValueError("Sync token are not supported")
  319. return token, self.list()
  320. def list(self):
  321. """List collection items."""
  322. raise NotImplementedError
  323. def get(self, href):
  324. """Fetch a single item."""
  325. raise NotImplementedError
  326. def get_multi(self, hrefs):
  327. """Fetch multiple items. Duplicate hrefs must be ignored.
  328. DEPRECATED: use ``get_multi2`` instead
  329. """
  330. return (self.get(href) for href in set(hrefs))
  331. def get_multi2(self, hrefs):
  332. """Fetch multiple items.
  333. Functionally similar to ``get``, but might bring performance benefits
  334. on some storages when used cleverly. It's not required to return the
  335. requested items in the correct order. Duplicated hrefs can be ignored.
  336. Returns tuples with the href and the item or None if the item doesn't
  337. exist.
  338. """
  339. return ((href, self.get(href)) for href in hrefs)
  340. def get_all(self):
  341. """Fetch all items.
  342. Functionally similar to ``get``, but might bring performance benefits
  343. on some storages when used cleverly.
  344. """
  345. return map(self.get, self.list())
  346. def get_all_filtered(self, filters):
  347. """Fetch all items with optional filtering.
  348. This can largely improve performance of reports depending on
  349. the filters and this implementation.
  350. Returns tuples in the form ``(item, filters_matched)``.
  351. ``filters_matched`` is a bool that indicates if ``filters`` are fully
  352. matched.
  353. This returns all events by default
  354. """
  355. return ((item, False) for item in self.get_all())
  356. def pre_filtered_list(self, filters):
  357. """List collection items with optional pre filtering.
  358. DEPRECATED: use ``get_all_filtered`` instead
  359. """
  360. return self.get_all()
  361. def has(self, href):
  362. """Check if an item exists by its href.
  363. Functionally similar to ``get``, but might bring performance benefits
  364. on some storages when used cleverly.
  365. """
  366. return self.get(href) is not None
  367. def upload(self, href, vobject_item):
  368. """Upload a new or replace an existing item."""
  369. raise NotImplementedError
  370. def delete(self, href=None):
  371. """Delete an item.
  372. When ``href`` is ``None``, delete the collection.
  373. """
  374. raise NotImplementedError
  375. def get_meta(self, key=None):
  376. """Get metadata value for collection.
  377. Return the value of the property ``key``. If ``key`` is ``None`` return
  378. a dict with all properties
  379. """
  380. raise NotImplementedError
  381. def set_meta(self, props):
  382. """Set metadata values for collection.
  383. ``props`` a dict with updates for properties. If a value is empty, the
  384. property must be deleted.
  385. """
  386. raise NotImplementedError
  387. @property
  388. def last_modified(self):
  389. """Get the HTTP-datetime of when the collection was modified."""
  390. raise NotImplementedError
  391. def serialize(self):
  392. """Get the unicode string representing the whole collection."""
  393. if self.get_meta("tag") == "VCALENDAR":
  394. collection = vobject.iCalendar()
  395. for item in self.get_all():
  396. for content in ("vevent", "vtodo", "vjournal"):
  397. for component in getattr(item, "%s_list" % content, ()):
  398. collection.add(component)
  399. return collection.serialize()
  400. elif self.get_meta("tag") == "VADDRESSBOOK":
  401. return "".join(item.serialize() for item in self.get_all())
  402. return ""
  403. @classmethod
  404. @contextmanager
  405. def acquire_lock(cls, mode, user=None):
  406. """Set a context manager to lock the whole storage.
  407. ``mode`` must either be "r" for shared access or "w" for exclusive
  408. access.
  409. ``user`` is the name of the logged in user or empty.
  410. """
  411. raise NotImplementedError
  412. class Collection(BaseCollection):
  413. """Collection stored in several files per calendar."""
  414. _item_cache_tag = None
  415. def __init__(self, path, principal=None, folder=None):
  416. # DEPRECATED: Remove useless principal attribute
  417. if folder is None:
  418. folder = self._get_collection_root_folder()
  419. # Path should already be sanitized
  420. self.path = sanitize_path(path).strip("/")
  421. self.encoding = self.configuration.get("encoding", "stock")
  422. self._filesystem_path = path_to_filesystem(folder, self.path)
  423. self._props_path = os.path.join(
  424. self._filesystem_path, ".Radicale.props")
  425. self.owner = self.path.split("/", maxsplit=1)[0]
  426. if principal is None:
  427. principal = bool(self.path) and "/" not in self.path
  428. self.is_principal = principal
  429. self._meta_cache = None
  430. self._etag_cache = None
  431. if self._item_cache_tag is None:
  432. try:
  433. vobject_version = pkg_resources.require("vobject")[0].version
  434. self.logger.debug("VObject version: %r", vobject_version)
  435. except Exception as e:
  436. self.logger.warning(
  437. "VObject version not found: %s", e, exc_info=True)
  438. vobject_version = ""
  439. Collection._item_cache_tag = vobject_version.encode() + b"\0"
  440. @classmethod
  441. def _get_collection_root_folder(cls):
  442. filesystem_folder = os.path.expanduser(
  443. cls.configuration.get("storage", "filesystem_folder"))
  444. return os.path.join(filesystem_folder, "collection-root")
  445. @contextmanager
  446. def _atomic_write(self, path, mode="w", newline=None):
  447. directory = os.path.dirname(path)
  448. tmp = NamedTemporaryFile(
  449. mode=mode, dir=directory, delete=False, prefix=".Radicale.tmp-",
  450. newline=newline, encoding=None if "b" in mode else self.encoding)
  451. try:
  452. yield tmp
  453. self._fsync(tmp.fileno())
  454. tmp.close()
  455. os.replace(tmp.name, path)
  456. except:
  457. tmp.close()
  458. os.remove(tmp.name)
  459. raise
  460. self._sync_directory(directory)
  461. @staticmethod
  462. def _find_available_file_name(exists_fn, suffix=""):
  463. # Prevent infinite loop
  464. for _ in range(1000):
  465. file_name = "%016x" % getrandbits(64) + suffix
  466. if not exists_fn(file_name):
  467. return file_name
  468. # something is wrong with the PRNG
  469. raise RuntimeError("No unique random sequence found")
  470. @classmethod
  471. def _fsync(cls, fd):
  472. if cls.configuration.getboolean("storage", "filesystem_fsync"):
  473. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  474. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  475. else:
  476. os.fsync(fd)
  477. @classmethod
  478. def _sync_directory(cls, path):
  479. """Sync directory to disk.
  480. This only works on POSIX and does nothing on other systems.
  481. """
  482. if not cls.configuration.getboolean("storage", "filesystem_fsync"):
  483. return
  484. if os.name == "posix":
  485. fd = os.open(path, 0)
  486. try:
  487. cls._fsync(fd)
  488. finally:
  489. os.close(fd)
  490. @classmethod
  491. def _makedirs_synced(cls, filesystem_path):
  492. """Recursively create a directory and its parents in a sync'ed way.
  493. This method acts silently when the folder already exists.
  494. """
  495. if os.path.isdir(filesystem_path):
  496. return
  497. parent_filesystem_path = os.path.dirname(filesystem_path)
  498. # Prevent infinite loop
  499. if filesystem_path != parent_filesystem_path:
  500. # Create parent dirs recursively
  501. cls._makedirs_synced(parent_filesystem_path)
  502. # Possible race!
  503. os.makedirs(filesystem_path, exist_ok=True)
  504. cls._sync_directory(parent_filesystem_path)
  505. @classmethod
  506. def discover(cls, path, depth="0"):
  507. # Path should already be sanitized
  508. sane_path = sanitize_path(path).strip("/")
  509. attributes = sane_path.split("/")
  510. if not attributes[0]:
  511. attributes.pop()
  512. folder = cls._get_collection_root_folder()
  513. # Create the root collection
  514. cls._makedirs_synced(folder)
  515. try:
  516. filesystem_path = path_to_filesystem(folder, sane_path)
  517. except ValueError as e:
  518. # Path is unsafe
  519. cls.logger.debug("Unsafe path %r requested from storage: %s",
  520. sane_path, e, exc_info=True)
  521. return
  522. # Check if the path exists and if it leads to a collection or an item
  523. if not os.path.isdir(filesystem_path):
  524. if attributes and os.path.isfile(filesystem_path):
  525. href = attributes.pop()
  526. else:
  527. return
  528. else:
  529. href = None
  530. sane_path = "/".join(attributes)
  531. collection = cls(sane_path)
  532. if href:
  533. yield collection.get(href)
  534. return
  535. yield collection
  536. if depth == "0":
  537. return
  538. for item in collection.list():
  539. yield collection.get(item)
  540. for href in scandir(filesystem_path, only_dirs=True):
  541. if not is_safe_filesystem_path_component(href):
  542. if not href.startswith(".Radicale"):
  543. cls.logger.debug("Skipping collection %r in %r", href,
  544. sane_path)
  545. continue
  546. child_path = posixpath.join(sane_path, href)
  547. yield cls(child_path)
  548. @classmethod
  549. def create_collection(cls, href, collection=None, props=None):
  550. folder = cls._get_collection_root_folder()
  551. # Path should already be sanitized
  552. sane_path = sanitize_path(href).strip("/")
  553. filesystem_path = path_to_filesystem(folder, sane_path)
  554. if not props:
  555. props = {}
  556. if not props.get("tag") and collection:
  557. props["tag"] = collection[0].name
  558. if not props:
  559. cls._makedirs_synced(filesystem_path)
  560. return cls(sane_path)
  561. parent_dir = os.path.dirname(filesystem_path)
  562. cls._makedirs_synced(parent_dir)
  563. # Create a temporary directory with an unsafe name
  564. with TemporaryDirectory(
  565. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  566. # The temporary directory itself can't be renamed
  567. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  568. os.makedirs(tmp_filesystem_path)
  569. self = cls("/", folder=tmp_filesystem_path)
  570. self.set_meta(props)
  571. if collection:
  572. if props.get("tag") == "VCALENDAR":
  573. collection, = collection
  574. items = []
  575. for content in ("vevent", "vtodo", "vjournal"):
  576. items.extend(
  577. getattr(collection, "%s_list" % content, []))
  578. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  579. vobject_items = {}
  580. for uid, items in items_by_uid:
  581. new_collection = vobject.iCalendar()
  582. for item in items:
  583. new_collection.add(item)
  584. # href must comply to is_safe_filesystem_path_component
  585. # and no file name collisions must exist between hrefs
  586. href = self._find_available_file_name(
  587. vobject_items.get, suffix=".ics")
  588. vobject_items[href] = new_collection
  589. self._upload_all_nonatomic(vobject_items)
  590. elif props.get("tag") == "VCARD":
  591. vobject_items = {}
  592. for card in collection:
  593. # href must comply to is_safe_filesystem_path_component
  594. # and no file name collisions must exist between hrefs
  595. href = self._find_available_file_name(
  596. vobject_items.get, suffix=".vcf")
  597. vobject_items[href] = card
  598. self._upload_all_nonatomic(vobject_items)
  599. # This operation is not atomic on the filesystem level but it's
  600. # very unlikely that one rename operations succeeds while the
  601. # other fails or that only one gets written to disk.
  602. if os.path.exists(filesystem_path):
  603. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  604. os.rename(tmp_filesystem_path, filesystem_path)
  605. cls._sync_directory(parent_dir)
  606. return cls(sane_path)
  607. def upload_all_nonatomic(self, vobject_items):
  608. """DEPRECATED: Use ``_upload_all_nonatomic``"""
  609. return self._upload_all_nonatomic(vobject_items)
  610. def _upload_all_nonatomic(self, vobject_items):
  611. """Upload a new set of items.
  612. This takes a mapping of href and vobject items and
  613. uploads them nonatomic and without existence checks.
  614. """
  615. with contextlib.ExitStack() as stack:
  616. fs = []
  617. for href, item in vobject_items.items():
  618. if not is_safe_filesystem_path_component(href):
  619. raise UnsafePathError(href)
  620. path = path_to_filesystem(self._filesystem_path, href)
  621. fs.append(stack.enter_context(
  622. open(path, "w", encoding=self.encoding, newline="")))
  623. fs[-1].write(item.serialize())
  624. # sync everything at once because it's slightly faster.
  625. for f in fs:
  626. self._fsync(f.fileno())
  627. self._sync_directory(self._filesystem_path)
  628. @classmethod
  629. def move(cls, item, to_collection, to_href):
  630. if not is_safe_filesystem_path_component(to_href):
  631. raise UnsafePathError(to_href)
  632. os.replace(
  633. path_to_filesystem(item.collection._filesystem_path, item.href),
  634. path_to_filesystem(to_collection._filesystem_path, to_href))
  635. cls._sync_directory(to_collection._filesystem_path)
  636. if item.collection._filesystem_path != to_collection._filesystem_path:
  637. cls._sync_directory(item.collection._filesystem_path)
  638. # Track the change
  639. to_collection._update_history_etag(to_href, item)
  640. item.collection._update_history_etag(item.href, None)
  641. to_collection._clean_history_cache()
  642. if item.collection._filesystem_path != to_collection._filesystem_path:
  643. item.collection._clean_history_cache()
  644. @classmethod
  645. def _clean_cache(cls, folder, names, max_age=None):
  646. """Delete all ``names`` in ``folder`` that are older than ``max_age``.
  647. """
  648. age_limit = time.time() - max_age if max_age is not None else None
  649. modified = False
  650. for name in names:
  651. if not is_safe_filesystem_path_component(name):
  652. continue
  653. if age_limit is not None:
  654. try:
  655. # Race: Another process might have deleted the file.
  656. mtime = os.path.getmtime(os.path.join(folder, name))
  657. except FileNotFoundError:
  658. continue
  659. if mtime > age_limit:
  660. continue
  661. cls.logger.debug("Found expired item in cache: %r", name)
  662. # Race: Another process might have deleted or locked the
  663. # file.
  664. try:
  665. os.remove(os.path.join(folder, name))
  666. except (FileNotFoundError, PermissionError):
  667. continue
  668. modified = True
  669. if modified:
  670. cls._sync_directory(folder)
  671. def _update_history_etag(self, href, item):
  672. """Updates and retrieves the history etag from the history cache.
  673. The history cache contains a file for each current and deleted item
  674. of the collection. These files contain the etag of the item (empty
  675. string for deleted items) and a history etag, which is a hash over
  676. the previous history etag and the etag separated by "/".
  677. """
  678. history_folder = os.path.join(self._filesystem_path,
  679. ".Radicale.cache", "history")
  680. try:
  681. with open(os.path.join(history_folder, href), "rb") as f:
  682. cache_etag, history_etag = pickle.load(f)
  683. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  684. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  685. self.logger.warning(
  686. "Failed to load history cache entry %r in %r: %s",
  687. href, self.path, e, exc_info=True)
  688. cache_etag = ""
  689. # Initialize with random data to prevent collisions with cleaned
  690. # expired items.
  691. history_etag = binascii.hexlify(os.urandom(16)).decode("ascii")
  692. etag = item.etag if item else ""
  693. if etag != cache_etag:
  694. self._makedirs_synced(history_folder)
  695. history_etag = get_etag(history_etag + "/" + etag).strip("\"")
  696. try:
  697. # Race: Other processes might have created and locked the file.
  698. with self._atomic_write(os.path.join(history_folder, href),
  699. "wb") as f:
  700. pickle.dump([etag, history_etag], f)
  701. except PermissionError:
  702. pass
  703. return history_etag
  704. def _get_deleted_history_hrefs(self):
  705. """Returns the hrefs of all deleted items that are still in the
  706. history cache."""
  707. history_folder = os.path.join(self._filesystem_path,
  708. ".Radicale.cache", "history")
  709. try:
  710. for href in scandir(history_folder):
  711. if not is_safe_filesystem_path_component(href):
  712. continue
  713. if os.path.isfile(os.path.join(self._filesystem_path, href)):
  714. continue
  715. yield href
  716. except FileNotFoundError:
  717. pass
  718. def _clean_history_cache(self):
  719. # Delete all expired cache entries of deleted items.
  720. history_folder = os.path.join(self._filesystem_path,
  721. ".Radicale.cache", "history")
  722. self._clean_cache(history_folder, self._get_deleted_history_hrefs(),
  723. max_age=self.configuration.getint(
  724. "storage", "max_sync_token_age"))
  725. def sync(self, old_token=None):
  726. # The sync token has the form http://radicale.org/ns/sync/TOKEN_NAME
  727. # where TOKEN_NAME is the md5 hash of all history etags of present and
  728. # past items of the collection.
  729. def check_token_name(token_name):
  730. if len(token_name) != 32:
  731. return False
  732. for c in token_name:
  733. if c not in "0123456789abcdef":
  734. return False
  735. return True
  736. old_token_name = None
  737. if old_token:
  738. # Extract the token name from the sync token
  739. if not old_token.startswith("http://radicale.org/ns/sync/"):
  740. raise ValueError("Malformed token: %r" % old_token)
  741. old_token_name = old_token[len("http://radicale.org/ns/sync/"):]
  742. if not check_token_name(old_token_name):
  743. raise ValueError("Malformed token: %r" % old_token)
  744. # Get the current state and sync-token of the collection.
  745. state = {}
  746. token_name_hash = md5()
  747. # Find the history of all existing and deleted items
  748. for href, item in chain(
  749. ((item.href, item) for item in self.get_all()),
  750. ((href, None) for href in self._get_deleted_history_hrefs())):
  751. history_etag = self._update_history_etag(href, item)
  752. state[href] = history_etag
  753. token_name_hash.update((href + "/" + history_etag).encode("utf-8"))
  754. token_name = token_name_hash.hexdigest()
  755. token = "http://radicale.org/ns/sync/%s" % token_name
  756. if token_name == old_token_name:
  757. # Nothing changed
  758. return token, ()
  759. token_folder = os.path.join(self._filesystem_path,
  760. ".Radicale.cache", "sync-token")
  761. token_path = os.path.join(token_folder, token_name)
  762. old_state = {}
  763. if old_token_name:
  764. # load the old token state
  765. old_token_path = os.path.join(token_folder, old_token_name)
  766. try:
  767. # Race: Another process might have deleted the file.
  768. with open(old_token_path, "rb") as f:
  769. old_state = pickle.load(f)
  770. except (FileNotFoundError, pickle.UnpicklingError,
  771. ValueError) as e:
  772. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  773. self.logger.warning(
  774. "Failed to load stored sync token %r in %r: %s",
  775. old_token_name, self.path, e, exc_info=True)
  776. # Delete the damaged file
  777. try:
  778. os.remove(old_token_path)
  779. except (FileNotFoundError, PermissionError):
  780. pass
  781. raise ValueError("Token not found: %r" % old_token)
  782. # write the new token state or update the modification time of
  783. # existing token state
  784. if not os.path.exists(token_path):
  785. self._makedirs_synced(token_folder)
  786. try:
  787. # Race: Other processes might have created and locked the file.
  788. with self._atomic_write(token_path, "wb") as f:
  789. pickle.dump(state, f)
  790. except PermissionError:
  791. pass
  792. else:
  793. # clean up old sync tokens and item cache
  794. self._clean_cache(token_folder, os.listdir(token_folder),
  795. max_age=self.configuration.getint(
  796. "storage", "max_sync_token_age"))
  797. self._clean_history_cache()
  798. else:
  799. # Try to update the modification time
  800. try:
  801. # Race: Another process might have deleted the file.
  802. os.utime(token_path)
  803. except FileNotFoundError:
  804. pass
  805. changes = []
  806. # Find all new, changed and deleted (that are still in the item cache)
  807. # items
  808. for href, history_etag in state.items():
  809. if history_etag != old_state.get(href):
  810. changes.append(href)
  811. # Find all deleted items that are no longer in the item cache
  812. for href, history_etag in old_state.items():
  813. if href not in state:
  814. changes.append(href)
  815. return token, changes
  816. def list(self):
  817. for href in scandir(self._filesystem_path, only_files=True):
  818. if not is_safe_filesystem_path_component(href):
  819. if not href.startswith(".Radicale"):
  820. self.logger.debug(
  821. "Skipping item %r in %r", href, self.path)
  822. continue
  823. yield href
  824. _item_cache_cleaned = False
  825. def get(self, href, verify_href=True):
  826. item, metadata = self._get_with_metadata(href, verify_href=verify_href)
  827. return item
  828. def _get_with_metadata(self, href, verify_href=True):
  829. """Like ``get`` but additonally returns the following metadata:
  830. tag, start, end: see ``xmlutils.find_tag_and_time_range``. If
  831. extraction of the metadata failed, the values are all ``None``."""
  832. if verify_href:
  833. try:
  834. if not is_safe_filesystem_path_component(href):
  835. raise UnsafePathError(href)
  836. path = path_to_filesystem(self._filesystem_path, href)
  837. except ValueError as e:
  838. self.logger.debug(
  839. "Can't translate name %r safely to filesystem in %r: %s",
  840. href, self.path, e, exc_info=True)
  841. return None, None
  842. else:
  843. path = os.path.join(self._filesystem_path, href)
  844. try:
  845. with open(path, "rb") as f:
  846. btext = f.read()
  847. except (FileNotFoundError, IsADirectoryError):
  848. return None, None
  849. # The hash of the component in the file system. This is used to check,
  850. # if the entry in the cache is still valid.
  851. input_hash = md5()
  852. input_hash.update(self._item_cache_tag)
  853. input_hash.update(btext)
  854. input_hash = input_hash.hexdigest()
  855. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
  856. "item")
  857. try:
  858. with open(os.path.join(cache_folder, href), "rb") as f:
  859. cinput_hash, cetag, ctext, ctag, cstart, cend = pickle.load(f)
  860. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  861. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  862. self.logger.warning(
  863. "Failed to load item cache entry %r in %r: %s",
  864. href, self.path, e, exc_info=True)
  865. cinput_hash = cetag = ctext = ctag = cstart = cend = None
  866. vobject_item = None
  867. if input_hash != cinput_hash:
  868. try:
  869. vobject_item = Item(self, href=href,
  870. text=btext.decode(self.encoding)).item
  871. check_item(vobject_item)
  872. except Exception as e:
  873. raise RuntimeError("Failed to load item %r in %r: %s" %
  874. (href, self.path, e)) from e
  875. # Serialize the object again, to normalize the text representation.
  876. # The storage may have been edited externally.
  877. ctext = vobject_item.serialize()
  878. cetag = get_etag(ctext)
  879. try:
  880. try:
  881. ctag, cstart, cend = xmlutils.find_tag_and_time_range(
  882. vobject_item)
  883. except xmlutils.VObjectBugException as e:
  884. # HACK: Extraction of metadata failed, because of bugs in
  885. # VObject.
  886. self.logger.warning(
  887. "Failed to find tag and time range of item %r from %r "
  888. "(Bug in VObject): %s", href, self.path, e,
  889. exc_info=True)
  890. ctag = xmlutils.find_tag(vobject_item)
  891. cstart = xmlutils.TIMESTAMP_MIN
  892. cend = xmlutils.TIMESTAMP_MAX
  893. except Exception as e:
  894. raise RuntimeError("Failed to find tag and time range of item "
  895. "%r from %r: %s" % (href, self.path,
  896. e)) from e
  897. self._makedirs_synced(cache_folder)
  898. try:
  899. # Race: Other processes might have created and locked the
  900. # file.
  901. with self._atomic_write(os.path.join(cache_folder, href),
  902. "wb") as f:
  903. pickle.dump((input_hash, cetag, ctext,
  904. ctag, cstart, cend), f)
  905. except PermissionError:
  906. pass
  907. # Clean cache entries (max once per request)
  908. # This happens once after new uploads, or if the data in the
  909. # file system was edited externally.
  910. if not self._item_cache_cleaned:
  911. self._item_cache_cleaned = True
  912. self._clean_cache(cache_folder, (
  913. href for href in scandir(cache_folder) if not
  914. os.path.isfile(os.path.join(self._filesystem_path, href))))
  915. last_modified = time.strftime(
  916. "%a, %d %b %Y %H:%M:%S GMT",
  917. time.gmtime(os.path.getmtime(path)))
  918. return Item(self, href=href, last_modified=last_modified, etag=cetag,
  919. text=ctext, item=vobject_item), (ctag, cstart, cend)
  920. def get_multi2(self, hrefs):
  921. # It's faster to check for file name collissions here, because
  922. # we only need to call os.listdir once.
  923. files = None
  924. for href in hrefs:
  925. if files is None:
  926. # List dir after hrefs returned one item, the iterator may be
  927. # empty and the for-loop is never executed.
  928. files = os.listdir(self._filesystem_path)
  929. path = os.path.join(self._filesystem_path, href)
  930. if (not is_safe_filesystem_path_component(href) or
  931. href not in files and os.path.lexists(path)):
  932. self.logger.debug(
  933. "Can't translate name safely to filesystem: %r", href)
  934. yield (href, None)
  935. else:
  936. yield (href, self.get(href, verify_href=False))
  937. def get_all(self):
  938. # We don't need to check for collissions, because the the file names
  939. # are from os.listdir.
  940. return (self.get(href, verify_href=False) for href in self.list())
  941. def get_all_filtered(self, filters):
  942. tag, start, end, simple = xmlutils.simplify_prefilters(filters)
  943. if not tag:
  944. # no filter
  945. yield from ((item, simple) for item in self.get_all())
  946. return
  947. for item, (itag, istart, iend) in (
  948. self._get_with_metadata(href, verify_href=False)
  949. for href in self.list()):
  950. if tag == itag and istart < end and iend > start:
  951. yield item, simple and (start <= istart or iend <= end)
  952. def upload(self, href, vobject_item):
  953. if not is_safe_filesystem_path_component(href):
  954. raise UnsafePathError(href)
  955. path = path_to_filesystem(self._filesystem_path, href)
  956. item = Item(self, href=href, item=vobject_item)
  957. with self._atomic_write(path, newline="") as fd:
  958. fd.write(item.serialize())
  959. # Track the change
  960. self._update_history_etag(href, item)
  961. self._clean_history_cache()
  962. return item
  963. def delete(self, href=None):
  964. if href is None:
  965. # Delete the collection
  966. parent_dir = os.path.dirname(self._filesystem_path)
  967. try:
  968. os.rmdir(self._filesystem_path)
  969. except OSError:
  970. with TemporaryDirectory(
  971. prefix=".Radicale.tmp-", dir=parent_dir) as tmp:
  972. os.rename(self._filesystem_path, os.path.join(
  973. tmp, os.path.basename(self._filesystem_path)))
  974. self._sync_directory(parent_dir)
  975. else:
  976. self._sync_directory(parent_dir)
  977. else:
  978. # Delete an item
  979. if not is_safe_filesystem_path_component(href):
  980. raise UnsafePathError(href)
  981. path = path_to_filesystem(self._filesystem_path, href)
  982. if not os.path.isfile(path):
  983. raise ComponentNotFoundError(href)
  984. os.remove(path)
  985. self._sync_directory(os.path.dirname(path))
  986. # Track the change
  987. self._update_history_etag(href, None)
  988. self._clean_history_cache()
  989. def get_meta(self, key=None):
  990. # reuse cached value if the storage is read-only
  991. if self._writer or self._meta_cache is None:
  992. try:
  993. with open(self._props_path, encoding=self.encoding) as f:
  994. self._meta_cache = json.load(f)
  995. except FileNotFoundError:
  996. self._meta_cache = {}
  997. except ValueError as e:
  998. raise RuntimeError("Failed to load properties of collect"
  999. "ion %r: %s" % (self.path, e)) from e
  1000. return self._meta_cache.get(key) if key else self._meta_cache
  1001. def set_meta(self, props):
  1002. new_props = self.get_meta()
  1003. new_props.update(props)
  1004. for key in tuple(new_props.keys()):
  1005. if not new_props[key]:
  1006. del new_props[key]
  1007. with self._atomic_write(self._props_path, "w") as f:
  1008. json.dump(new_props, f)
  1009. @property
  1010. def last_modified(self):
  1011. relevant_files = chain(
  1012. (self._filesystem_path,),
  1013. (self._props_path,) if os.path.exists(self._props_path) else (),
  1014. (os.path.join(self._filesystem_path, h) for h in self.list()))
  1015. last = max(map(os.path.getmtime, relevant_files))
  1016. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  1017. def serialize(self):
  1018. # serialize collection
  1019. if self.get_meta("tag") == "VCALENDAR":
  1020. in_vcalendar = False
  1021. vtimezones = ""
  1022. included_tzids = set()
  1023. vtimezone = []
  1024. tzid = None
  1025. components = ""
  1026. # Concatenate all child elements of VCALENDAR from all items
  1027. # together, while preventing duplicated VTIMEZONE entries.
  1028. # VTIMEZONEs are only distinguished by their TZID, if different
  1029. # timezones share the same TZID this produces errornous ouput.
  1030. # VObject fails at this too.
  1031. for item in self.get_all():
  1032. depth = 0
  1033. for line in item.serialize().split("\r\n"):
  1034. if line.startswith("BEGIN:"):
  1035. depth += 1
  1036. if depth == 1 and line == "BEGIN:VCALENDAR":
  1037. in_vcalendar = True
  1038. elif in_vcalendar:
  1039. if depth == 1 and line.startswith("END:"):
  1040. in_vcalendar = False
  1041. if depth == 2 and line == "BEGIN:VTIMEZONE":
  1042. vtimezone.append(line)
  1043. elif vtimezone:
  1044. vtimezone.append(line)
  1045. if depth == 2 and line.startswith("TZID:"):
  1046. tzid = line[len("TZID:"):]
  1047. elif depth == 2 and line.startswith("END:"):
  1048. if tzid is None or tzid not in included_tzids:
  1049. if vtimezones:
  1050. vtimezones += "\r\n"
  1051. vtimezones += "\r\n".join(vtimezone)
  1052. included_tzids.add(tzid)
  1053. vtimezone.clear()
  1054. tzid = None
  1055. elif depth >= 2:
  1056. if components:
  1057. components += "\r\n"
  1058. components += line
  1059. if line.startswith("END:"):
  1060. depth -= 1
  1061. return "\r\n".join(filter(bool, (
  1062. "BEGIN:VCALENDAR",
  1063. "VERSION:2.0",
  1064. "PRODID:-//PYVOBJECT//NONSGML Version 1//EN",
  1065. vtimezones,
  1066. components,
  1067. "END:VCALENDAR")))
  1068. elif self.get_meta("tag") == "VADDRESSBOOK":
  1069. return "".join((item.serialize() for item in self.get_all()))
  1070. return ""
  1071. @property
  1072. def etag(self):
  1073. # reuse cached value if the storage is read-only
  1074. if self._writer or self._etag_cache is None:
  1075. etag = md5()
  1076. for item in self.get_all():
  1077. etag.update((item.href + "/" + item.etag).encode("utf-8"))
  1078. self._etag_cache = '"%s"' % etag.hexdigest()
  1079. return self._etag_cache
  1080. _lock = threading.Lock()
  1081. _waiters = []
  1082. _lock_file = None
  1083. _lock_file_locked = False
  1084. _readers = 0
  1085. _writer = False
  1086. @classmethod
  1087. @contextmanager
  1088. def acquire_lock(cls, mode, user=None):
  1089. def condition():
  1090. if mode == "r":
  1091. return not cls._writer
  1092. else:
  1093. return not cls._writer and cls._readers == 0
  1094. file_locking = cls.configuration.getboolean("storage",
  1095. "filesystem_locking")
  1096. folder = os.path.expanduser(cls.configuration.get(
  1097. "storage", "filesystem_folder"))
  1098. # Use a primitive lock which only works within one process as a
  1099. # precondition for inter-process file-based locking
  1100. with cls._lock:
  1101. if cls._waiters or not condition():
  1102. # Use FIFO for access requests
  1103. waiter = threading.Condition(lock=cls._lock)
  1104. cls._waiters.append(waiter)
  1105. while True:
  1106. waiter.wait()
  1107. if condition():
  1108. break
  1109. cls._waiters.pop(0)
  1110. if mode == "r":
  1111. cls._readers += 1
  1112. # Notify additional potential readers
  1113. if cls._waiters:
  1114. cls._waiters[0].notify()
  1115. else:
  1116. cls._writer = True
  1117. if not cls._lock_file:
  1118. cls._makedirs_synced(folder)
  1119. lock_path = os.path.join(folder, ".Radicale.lock")
  1120. cls._lock_file = open(lock_path, "w+")
  1121. if file_locking and not cls._lock_file_locked:
  1122. if os.name == "nt":
  1123. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  1124. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  1125. overlapped = Overlapped()
  1126. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  1127. raise RuntimeError("Locking the storage failed "
  1128. "(can be disabled in the config): "
  1129. "%s" % ctypes.FormatError())
  1130. elif os.name == "posix":
  1131. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  1132. try:
  1133. fcntl.flock(cls._lock_file.fileno(), _cmd)
  1134. except OSError as e:
  1135. raise RuntimeError("Locking the storage failed "
  1136. "(can be disabled in the config): "
  1137. "%s" % e) from e
  1138. else:
  1139. raise RuntimeError("Locking the storage failed "
  1140. "(can be disabled in the config): "
  1141. "Unsupported operating system")
  1142. cls._lock_file_locked = True
  1143. try:
  1144. yield
  1145. # execute hook
  1146. hook = cls.configuration.get("storage", "hook")
  1147. if mode == "w" and hook:
  1148. cls.logger.debug("Running hook")
  1149. subprocess.check_call(
  1150. hook % {"user": shlex.quote(user or "Anonymous")},
  1151. shell=True, cwd=folder)
  1152. finally:
  1153. with cls._lock:
  1154. if mode == "r":
  1155. cls._readers -= 1
  1156. else:
  1157. cls._writer = False
  1158. if file_locking and cls._readers == 0:
  1159. if os.name == "nt":
  1160. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  1161. overlapped = Overlapped()
  1162. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  1163. raise RuntimeError("Unlocking the storage failed: "
  1164. "%s" % ctypes.FormatError())
  1165. elif os.name == "posix":
  1166. try:
  1167. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  1168. except OSError as e:
  1169. raise RuntimeError("Unlocking the storage failed: "
  1170. "%s" % e) from e
  1171. else:
  1172. raise RuntimeError("Unlocking the storage failed: "
  1173. "Unsupported operating system")
  1174. cls._lock_file_locked = False
  1175. if cls._waiters:
  1176. cls._waiters[0].notify()
  1177. if (cls.configuration.getboolean(
  1178. "storage", "filesystem_close_lock_file") and
  1179. cls._readers == 0 and not cls._waiters):
  1180. cls._lock_file.close()
  1181. cls._lock_file = None