storage.py 55 KB

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