storage.py 64 KB

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