storage.py 61 KB

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