storage.py 55 KB

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