storage.py 64 KB

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