storage.py 55 KB

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