storage.py 55 KB

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