storage.py 65 KB

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