storage.py 52 KB

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