storage.py 65 KB

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