storage.py 62 KB

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