storage.py 64 KB

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