storage.py 62 KB

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