1
0

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. elif vobject_item.name == "VLIST":
  151. # Custom format used by SOGo Connector to store lists of contacts
  152. pass
  153. else:
  154. raise ValueError("Unknown item type: %r" % vobject_item.name)
  155. def random_uuid4():
  156. """Generate a pseudo-random UUID"""
  157. r = "%016x" % getrandbits(128)
  158. return "%s-%s-%s-%s-%s" % (r[:8], r[8:12], r[12:16], r[16:20], r[20:])
  159. def scandir(path, only_dirs=False, only_files=False):
  160. """Iterator for directory elements. (For compatibility with Python < 3.5)
  161. ``only_dirs`` only return directories
  162. ``only_files`` only return files
  163. """
  164. if sys.version_info >= (3, 5):
  165. for entry in os.scandir(path):
  166. if ((not only_files or entry.is_file()) and
  167. (not only_dirs or entry.is_dir())):
  168. yield entry.name
  169. else:
  170. for name in os.listdir(path):
  171. p = os.path.join(path, name)
  172. if ((not only_files or os.path.isfile(p)) and
  173. (not only_dirs or os.path.isdir(p))):
  174. yield name
  175. def get_etag(text):
  176. """Etag from collection or item.
  177. Encoded as quoted-string (see RFC 2616).
  178. """
  179. etag = md5()
  180. etag.update(text.encode("utf-8"))
  181. return '"%s"' % etag.hexdigest()
  182. def get_uid(vobject_component):
  183. """UID value of an item if defined."""
  184. return ((hasattr(vobject_component, "uid") or None) and
  185. vobject_component.uid.value)
  186. def get_uid_from_object(vobject_item):
  187. """UID value of an calendar/addressbook object."""
  188. if vobject_item.name == "VCALENDAR":
  189. if hasattr(vobject_item, "vevent"):
  190. return get_uid(vobject_item.vevent)
  191. if hasattr(vobject_item, "vjournal"):
  192. return get_uid(vobject_item.vjournal)
  193. if hasattr(vobject_item, "vtodo"):
  194. return get_uid(vobject_item.vtodo)
  195. elif vobject_item.name == "VCARD":
  196. return get_uid(vobject_item)
  197. return None
  198. def sanitize_path(path):
  199. """Make path absolute with leading slash to prevent access to other data.
  200. Preserve a potential trailing slash.
  201. """
  202. trailing_slash = "/" if path.endswith("/") else ""
  203. path = posixpath.normpath(path)
  204. new_path = "/"
  205. for part in path.split("/"):
  206. if not is_safe_path_component(part):
  207. continue
  208. new_path = posixpath.join(new_path, part)
  209. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  210. return new_path + trailing_slash
  211. def is_safe_path_component(path):
  212. """Check if path is a single component of a path.
  213. Check that the path is safe to join too.
  214. """
  215. return path and "/" not in path and path not in (".", "..")
  216. def is_safe_filesystem_path_component(path):
  217. """Check if path is a single component of a local and posix filesystem
  218. path.
  219. Check that the path is safe to join too.
  220. """
  221. return (
  222. path and not os.path.splitdrive(path)[0] and
  223. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  224. not path.startswith(".") and not path.endswith("~") and
  225. is_safe_path_component(path))
  226. def path_to_filesystem(root, *paths):
  227. """Convert path to a local filesystem path relative to base_folder.
  228. `root` must be a secure filesystem path, it will be prepend to the path.
  229. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  230. """
  231. paths = [sanitize_path(path).strip("/") for path in paths]
  232. safe_path = root
  233. for path in paths:
  234. if not path:
  235. continue
  236. for part in path.split("/"):
  237. if not is_safe_filesystem_path_component(part):
  238. raise UnsafePathError(part)
  239. safe_path_parent = safe_path
  240. safe_path = os.path.join(safe_path, part)
  241. # Check for conflicting files (e.g. case-insensitive file systems
  242. # or short names on Windows file systems)
  243. if (os.path.lexists(safe_path) and
  244. part not in scandir(safe_path_parent)):
  245. raise CollidingPathError(part)
  246. return safe_path
  247. class UnsafePathError(ValueError):
  248. def __init__(self, path):
  249. message = "Can't translate name safely to filesystem: %r" % path
  250. super().__init__(message)
  251. class CollidingPathError(ValueError):
  252. def __init__(self, path):
  253. message = "File name collision: %r" % path
  254. super().__init__(message)
  255. class ComponentExistsError(ValueError):
  256. def __init__(self, path):
  257. message = "Component already exists: %r" % path
  258. super().__init__(message)
  259. class ComponentNotFoundError(ValueError):
  260. def __init__(self, path):
  261. message = "Component doesn't exist: %r" % path
  262. super().__init__(message)
  263. class Item:
  264. def __init__(self, collection, item=None, href=None, last_modified=None,
  265. text=None, etag=None, uid=None):
  266. """Initialize an item.
  267. ``collection`` the parent collection.
  268. ``href`` the href of the item.
  269. ``last_modified`` the HTTP-datetime of when the item was modified.
  270. ``text`` the text representation of the item (optional if ``item`` is
  271. set).
  272. ``item`` the vobject item (optional if ``text`` is set).
  273. ``etag`` the etag of the item (optional). See ``get_etag``.
  274. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  275. """
  276. if text is None and item is None:
  277. raise ValueError("at least one of 'text' or 'item' must be set")
  278. self.collection = collection
  279. self.href = href
  280. self.last_modified = last_modified
  281. self._text = text
  282. self._item = item
  283. self._etag = etag
  284. self._uid = uid
  285. def __getattr__(self, attr):
  286. return getattr(self.item, attr)
  287. def serialize(self):
  288. if self._text is None:
  289. self._text = self.item.serialize()
  290. return self._text
  291. @property
  292. def item(self):
  293. if self._item is None:
  294. try:
  295. items = tuple(vobject.readComponents(self._text))
  296. if len(items) != 1:
  297. raise RuntimeError(
  298. "Content contains %d components" % len(items))
  299. self._item = items[0]
  300. except Exception as e:
  301. raise RuntimeError("Failed to parse item %r from %r: %s" %
  302. (self.href, self.collection.path, e)) from e
  303. return self._item
  304. @property
  305. def etag(self):
  306. """Encoded as quoted-string (see RFC 2616)."""
  307. if self._etag is None:
  308. self._etag = get_etag(self.serialize())
  309. return self._etag
  310. @property
  311. def uid(self):
  312. if self._uid is None:
  313. self._uid = get_uid_from_object(self.item)
  314. return self._uid
  315. class BaseCollection:
  316. # Overriden on copy by the "load" function
  317. configuration = None
  318. logger = None
  319. # Properties of instance
  320. """The sanitized path of the collection without leading or trailing ``/``.
  321. """
  322. path = ""
  323. """The owner of the collection. (``path.split("/", maxsplit=1)[0]``)"""
  324. owner = ""
  325. """Collection is a principal. (``bool(path) and "/" not in path``)"""
  326. is_principal = False
  327. @classmethod
  328. def discover(cls, path, depth="0"):
  329. """Discover a list of collections under the given ``path``.
  330. ``path`` is sanitized.
  331. If ``depth`` is "0", only the actual object under ``path`` is
  332. returned.
  333. If ``depth`` is anything but "0", it is considered as "1" and direct
  334. children are included in the result.
  335. The root collection "/" must always exist.
  336. """
  337. raise NotImplementedError
  338. @classmethod
  339. def move(cls, item, to_collection, to_href):
  340. """Move an object.
  341. ``item`` is the item to move.
  342. ``to_collection`` is the target collection.
  343. ``to_href`` is the target name in ``to_collection``. An item with the
  344. same name might already exist.
  345. """
  346. if item.collection.path == to_collection.path and item.href == to_href:
  347. return
  348. to_collection.upload(to_href, item.item)
  349. item.collection.delete(item.href)
  350. @property
  351. def etag(self):
  352. """Encoded as quoted-string (see RFC 2616)."""
  353. return get_etag(self.serialize())
  354. @classmethod
  355. def create_collection(cls, href, collection=None, props=None):
  356. """Create a collection.
  357. ``href`` is the sanitized path.
  358. If the collection already exists and neither ``collection`` nor
  359. ``props`` are set, this method shouldn't do anything. Otherwise the
  360. existing collection must be replaced.
  361. ``collection`` is a list of vobject components.
  362. ``props`` are metadata values for the collection.
  363. ``props["tag"]`` is the type of collection (VCALENDAR or
  364. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  365. collection.
  366. """
  367. raise NotImplementedError
  368. def sync(self, old_token=None):
  369. """Get the current sync token and changed items for synchronization.
  370. ``old_token`` an old sync token which is used as the base of the
  371. delta update. If sync token is missing, all items are returned.
  372. ValueError is raised for invalid or old tokens.
  373. WARNING: This simple default implementation treats all sync-token as
  374. invalid. It adheres to the specification but some clients
  375. (e.g. InfCloud) don't like it. Subclasses should provide a
  376. more sophisticated implementation.
  377. """
  378. token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"")
  379. if old_token:
  380. raise ValueError("Sync token are not supported")
  381. return token, self.list()
  382. def list(self):
  383. """List collection items."""
  384. raise NotImplementedError
  385. def get(self, href):
  386. """Fetch a single item."""
  387. raise NotImplementedError
  388. def get_multi(self, hrefs):
  389. """Fetch multiple items. Duplicate hrefs must be ignored.
  390. DEPRECATED: use ``get_multi2`` instead
  391. """
  392. return (self.get(href) for href in set(hrefs))
  393. def get_multi2(self, hrefs):
  394. """Fetch multiple items.
  395. Functionally similar to ``get``, but might bring performance benefits
  396. on some storages when used cleverly. It's not required to return the
  397. requested items in the correct order. Duplicated hrefs can be ignored.
  398. Returns tuples with the href and the item or None if the item doesn't
  399. exist.
  400. """
  401. return ((href, self.get(href)) for href in hrefs)
  402. def get_all(self):
  403. """Fetch all items.
  404. Functionally similar to ``get``, but might bring performance benefits
  405. on some storages when used cleverly.
  406. """
  407. return map(self.get, self.list())
  408. def get_all_filtered(self, filters):
  409. """Fetch all items with optional filtering.
  410. This can largely improve performance of reports depending on
  411. the filters and this implementation.
  412. Returns tuples in the form ``(item, filters_matched)``.
  413. ``filters_matched`` is a bool that indicates if ``filters`` are fully
  414. matched.
  415. This returns all events by default
  416. """
  417. return ((item, False) for item in self.get_all())
  418. def pre_filtered_list(self, filters):
  419. """List collection items with optional pre filtering.
  420. DEPRECATED: use ``get_all_filtered`` instead
  421. """
  422. return self.get_all()
  423. def has(self, href):
  424. """Check if an item exists by its href.
  425. Functionally similar to ``get``, but might bring performance benefits
  426. on some storages when used cleverly.
  427. """
  428. return self.get(href) is not None
  429. def upload(self, href, vobject_item):
  430. """Upload a new or replace an existing item."""
  431. raise NotImplementedError
  432. def delete(self, href=None):
  433. """Delete an item.
  434. When ``href`` is ``None``, delete the collection.
  435. """
  436. raise NotImplementedError
  437. def get_meta(self, key=None):
  438. """Get metadata value for collection.
  439. Return the value of the property ``key``. If ``key`` is ``None`` return
  440. a dict with all properties
  441. """
  442. raise NotImplementedError
  443. def set_meta(self, props):
  444. """Set metadata values for collection.
  445. ``props`` a dict with updates for properties. If a value is empty, the
  446. property must be deleted.
  447. """
  448. raise NotImplementedError
  449. @property
  450. def last_modified(self):
  451. """Get the HTTP-datetime of when the collection was modified."""
  452. raise NotImplementedError
  453. def serialize(self):
  454. """Get the unicode string representing the whole collection."""
  455. if self.get_meta("tag") == "VCALENDAR":
  456. collection = vobject.iCalendar()
  457. for item in self.get_all():
  458. for content in ("vevent", "vtodo", "vjournal"):
  459. for component in getattr(item, "%s_list" % content, ()):
  460. collection.add(component)
  461. return collection.serialize()
  462. elif self.get_meta("tag") == "VADDRESSBOOK":
  463. return "".join(item.serialize() for item in self.get_all())
  464. return ""
  465. @classmethod
  466. @contextmanager
  467. def acquire_lock(cls, mode, user=None):
  468. """Set a context manager to lock the whole storage.
  469. ``mode`` must either be "r" for shared access or "w" for exclusive
  470. access.
  471. ``user`` is the name of the logged in user or empty.
  472. """
  473. raise NotImplementedError
  474. class Collection(BaseCollection):
  475. """Collection stored in several files per calendar."""
  476. _item_cache_tag = None
  477. def __init__(self, path, principal=None, folder=None):
  478. # DEPRECATED: Remove useless principal attribute
  479. if folder is None:
  480. folder = self._get_collection_root_folder()
  481. # Path should already be sanitized
  482. self.path = sanitize_path(path).strip("/")
  483. self.encoding = self.configuration.get("encoding", "stock")
  484. self._filesystem_path = path_to_filesystem(folder, self.path)
  485. self._props_path = os.path.join(
  486. self._filesystem_path, ".Radicale.props")
  487. self.owner = self.path.split("/", maxsplit=1)[0]
  488. if principal is None:
  489. principal = bool(self.path) and "/" not in self.path
  490. self.is_principal = principal
  491. self._meta_cache = None
  492. self._etag_cache = None
  493. if self._item_cache_tag is None:
  494. try:
  495. vobject_version = pkg_resources.require("vobject")[0].version
  496. self.logger.debug("VObject version: %r", vobject_version)
  497. except Exception as e:
  498. self.logger.warning(
  499. "VObject version not found: %s", e, exc_info=True)
  500. vobject_version = ""
  501. Collection._item_cache_tag = vobject_version.encode() + b"\0"
  502. @classmethod
  503. def _get_collection_root_folder(cls):
  504. filesystem_folder = os.path.expanduser(
  505. cls.configuration.get("storage", "filesystem_folder"))
  506. return os.path.join(filesystem_folder, "collection-root")
  507. @contextmanager
  508. def _atomic_write(self, path, mode="w", newline=None):
  509. directory = os.path.dirname(path)
  510. tmp = NamedTemporaryFile(
  511. mode=mode, dir=directory, delete=False, prefix=".Radicale.tmp-",
  512. newline=newline, encoding=None if "b" in mode else self.encoding)
  513. try:
  514. yield tmp
  515. self._fsync(tmp.fileno())
  516. tmp.close()
  517. os.replace(tmp.name, path)
  518. except:
  519. tmp.close()
  520. os.remove(tmp.name)
  521. raise
  522. self._sync_directory(directory)
  523. @staticmethod
  524. def _find_available_file_name(exists_fn, suffix=""):
  525. # Prevent infinite loop
  526. for _ in range(1000):
  527. file_name = random_uuid4() + suffix
  528. if not exists_fn(file_name):
  529. return file_name
  530. # something is wrong with the PRNG
  531. raise RuntimeError("No unique random sequence found")
  532. @classmethod
  533. def _fsync(cls, fd):
  534. if cls.configuration.getboolean("storage", "filesystem_fsync"):
  535. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  536. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  537. else:
  538. os.fsync(fd)
  539. @classmethod
  540. def _sync_directory(cls, path):
  541. """Sync directory to disk.
  542. This only works on POSIX and does nothing on other systems.
  543. """
  544. if not cls.configuration.getboolean("storage", "filesystem_fsync"):
  545. return
  546. if os.name == "posix":
  547. try:
  548. fd = os.open(path, 0)
  549. try:
  550. cls._fsync(fd)
  551. finally:
  552. os.close(fd)
  553. except OSError as e:
  554. raise RuntimeError("Fsync'ing directory %r failed: %s" %
  555. (path, e)) from e
  556. @classmethod
  557. def _makedirs_synced(cls, filesystem_path):
  558. """Recursively create a directory and its parents in a sync'ed way.
  559. This method acts silently when the folder already exists.
  560. """
  561. if os.path.isdir(filesystem_path):
  562. return
  563. parent_filesystem_path = os.path.dirname(filesystem_path)
  564. # Prevent infinite loop
  565. if filesystem_path != parent_filesystem_path:
  566. # Create parent dirs recursively
  567. cls._makedirs_synced(parent_filesystem_path)
  568. # Possible race!
  569. os.makedirs(filesystem_path, exist_ok=True)
  570. cls._sync_directory(parent_filesystem_path)
  571. @classmethod
  572. def discover(cls, path, depth="0"):
  573. # Path should already be sanitized
  574. sane_path = sanitize_path(path).strip("/")
  575. attributes = sane_path.split("/")
  576. if not attributes[0]:
  577. attributes.pop()
  578. folder = cls._get_collection_root_folder()
  579. # Create the root collection
  580. cls._makedirs_synced(folder)
  581. try:
  582. filesystem_path = path_to_filesystem(folder, sane_path)
  583. except ValueError as e:
  584. # Path is unsafe
  585. cls.logger.debug("Unsafe path %r requested from storage: %s",
  586. sane_path, e, exc_info=True)
  587. return
  588. # Check if the path exists and if it leads to a collection or an item
  589. if not os.path.isdir(filesystem_path):
  590. if attributes and os.path.isfile(filesystem_path):
  591. href = attributes.pop()
  592. else:
  593. return
  594. else:
  595. href = None
  596. sane_path = "/".join(attributes)
  597. collection = cls(sane_path)
  598. if href:
  599. yield collection.get(href)
  600. return
  601. yield collection
  602. if depth == "0":
  603. return
  604. for item in collection.list():
  605. yield collection.get(item)
  606. for href in scandir(filesystem_path, only_dirs=True):
  607. if not is_safe_filesystem_path_component(href):
  608. if not href.startswith(".Radicale"):
  609. cls.logger.debug("Skipping collection %r in %r", href,
  610. sane_path)
  611. continue
  612. child_path = posixpath.join(sane_path, href)
  613. yield cls(child_path)
  614. @classmethod
  615. def create_collection(cls, href, collection=None, props=None):
  616. folder = cls._get_collection_root_folder()
  617. # Path should already be sanitized
  618. sane_path = sanitize_path(href).strip("/")
  619. filesystem_path = path_to_filesystem(folder, sane_path)
  620. if not props:
  621. cls._makedirs_synced(filesystem_path)
  622. return cls(sane_path)
  623. parent_dir = os.path.dirname(filesystem_path)
  624. cls._makedirs_synced(parent_dir)
  625. # Create a temporary directory with an unsafe name
  626. with TemporaryDirectory(
  627. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  628. # The temporary directory itself can't be renamed
  629. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  630. os.makedirs(tmp_filesystem_path)
  631. self = cls("/", folder=tmp_filesystem_path)
  632. self.set_meta(props)
  633. if collection:
  634. if props.get("tag") == "VCALENDAR":
  635. collection, = collection
  636. items = []
  637. for content in ("vevent", "vtodo", "vjournal"):
  638. items.extend(
  639. getattr(collection, "%s_list" % content, []))
  640. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  641. vobject_items = {}
  642. for uid, items in items_by_uid:
  643. new_collection = vobject.iCalendar()
  644. for item in items:
  645. new_collection.add(item)
  646. # href must comply to is_safe_filesystem_path_component
  647. # and no file name collisions must exist between hrefs
  648. href = self._find_available_file_name(
  649. vobject_items.get, suffix=".ics")
  650. vobject_items[href] = new_collection
  651. self._upload_all_nonatomic(vobject_items)
  652. elif props.get("tag") == "VADDRESSBOOK":
  653. vobject_items = {}
  654. for card in collection:
  655. # href must comply to is_safe_filesystem_path_component
  656. # and no file name collisions must exist between hrefs
  657. href = self._find_available_file_name(
  658. vobject_items.get, suffix=".vcf")
  659. vobject_items[href] = card
  660. self._upload_all_nonatomic(vobject_items)
  661. # This operation is not atomic on the filesystem level but it's
  662. # very unlikely that one rename operations succeeds while the
  663. # other fails or that only one gets written to disk.
  664. if os.path.exists(filesystem_path):
  665. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  666. os.rename(tmp_filesystem_path, filesystem_path)
  667. cls._sync_directory(parent_dir)
  668. return cls(sane_path)
  669. def upload_all_nonatomic(self, vobject_items):
  670. """DEPRECATED: Use ``_upload_all_nonatomic``"""
  671. return self._upload_all_nonatomic(vobject_items)
  672. def _upload_all_nonatomic(self, vobject_items):
  673. """Upload a new set of items.
  674. This takes a mapping of href and vobject items and
  675. uploads them nonatomic and without existence checks.
  676. """
  677. with contextlib.ExitStack() as stack:
  678. fs = []
  679. for href, item in vobject_items.items():
  680. if not is_safe_filesystem_path_component(href):
  681. raise UnsafePathError(href)
  682. path = path_to_filesystem(self._filesystem_path, href)
  683. fs.append(stack.enter_context(
  684. open(path, "w", encoding=self.encoding, newline="")))
  685. fs[-1].write(item.serialize())
  686. # sync everything at once because it's slightly faster.
  687. for f in fs:
  688. self._fsync(f.fileno())
  689. self._sync_directory(self._filesystem_path)
  690. @classmethod
  691. def move(cls, item, to_collection, to_href):
  692. if not is_safe_filesystem_path_component(to_href):
  693. raise UnsafePathError(to_href)
  694. os.replace(
  695. path_to_filesystem(item.collection._filesystem_path, item.href),
  696. path_to_filesystem(to_collection._filesystem_path, to_href))
  697. cls._sync_directory(to_collection._filesystem_path)
  698. if item.collection._filesystem_path != to_collection._filesystem_path:
  699. cls._sync_directory(item.collection._filesystem_path)
  700. # Track the change
  701. to_collection._update_history_etag(to_href, item)
  702. item.collection._update_history_etag(item.href, None)
  703. to_collection._clean_history_cache()
  704. if item.collection._filesystem_path != to_collection._filesystem_path:
  705. item.collection._clean_history_cache()
  706. @classmethod
  707. def _clean_cache(cls, folder, names, max_age=None):
  708. """Delete all ``names`` in ``folder`` that are older than ``max_age``.
  709. """
  710. age_limit = time.time() - max_age if max_age is not None else None
  711. modified = False
  712. for name in names:
  713. if not is_safe_filesystem_path_component(name):
  714. continue
  715. if age_limit is not None:
  716. try:
  717. # Race: Another process might have deleted the file.
  718. mtime = os.path.getmtime(os.path.join(folder, name))
  719. except FileNotFoundError:
  720. continue
  721. if mtime > age_limit:
  722. continue
  723. cls.logger.debug("Found expired item in cache: %r", name)
  724. # Race: Another process might have deleted or locked the
  725. # file.
  726. try:
  727. os.remove(os.path.join(folder, name))
  728. except (FileNotFoundError, PermissionError):
  729. continue
  730. modified = True
  731. if modified:
  732. cls._sync_directory(folder)
  733. def _update_history_etag(self, href, item):
  734. """Updates and retrieves the history etag from the history cache.
  735. The history cache contains a file for each current and deleted item
  736. of the collection. These files contain the etag of the item (empty
  737. string for deleted items) and a history etag, which is a hash over
  738. the previous history etag and the etag separated by "/".
  739. """
  740. history_folder = os.path.join(self._filesystem_path,
  741. ".Radicale.cache", "history")
  742. try:
  743. with open(os.path.join(history_folder, href), "rb") as f:
  744. cache_etag, history_etag = pickle.load(f)
  745. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  746. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  747. self.logger.warning(
  748. "Failed to load history cache entry %r in %r: %s",
  749. href, self.path, e, exc_info=True)
  750. cache_etag = ""
  751. # Initialize with random data to prevent collisions with cleaned
  752. # expired items.
  753. history_etag = binascii.hexlify(os.urandom(16)).decode("ascii")
  754. etag = item.etag if item else ""
  755. if etag != cache_etag:
  756. self._makedirs_synced(history_folder)
  757. history_etag = get_etag(history_etag + "/" + etag).strip("\"")
  758. try:
  759. # Race: Other processes might have created and locked the file.
  760. with self._atomic_write(os.path.join(history_folder, href),
  761. "wb") as f:
  762. pickle.dump([etag, history_etag], f)
  763. except PermissionError:
  764. pass
  765. return history_etag
  766. def _get_deleted_history_hrefs(self):
  767. """Returns the hrefs of all deleted items that are still in the
  768. history cache."""
  769. history_folder = os.path.join(self._filesystem_path,
  770. ".Radicale.cache", "history")
  771. try:
  772. for href in scandir(history_folder):
  773. if not is_safe_filesystem_path_component(href):
  774. continue
  775. if os.path.isfile(os.path.join(self._filesystem_path, href)):
  776. continue
  777. yield href
  778. except FileNotFoundError:
  779. pass
  780. def _clean_history_cache(self):
  781. # Delete all expired cache entries of deleted items.
  782. history_folder = os.path.join(self._filesystem_path,
  783. ".Radicale.cache", "history")
  784. self._clean_cache(history_folder, self._get_deleted_history_hrefs(),
  785. max_age=self.configuration.getint(
  786. "storage", "max_sync_token_age"))
  787. def sync(self, old_token=None):
  788. # The sync token has the form http://radicale.org/ns/sync/TOKEN_NAME
  789. # where TOKEN_NAME is the md5 hash of all history etags of present and
  790. # past items of the collection.
  791. def check_token_name(token_name):
  792. if len(token_name) != 32:
  793. return False
  794. for c in token_name:
  795. if c not in "0123456789abcdef":
  796. return False
  797. return True
  798. old_token_name = None
  799. if old_token:
  800. # Extract the token name from the sync token
  801. if not old_token.startswith("http://radicale.org/ns/sync/"):
  802. raise ValueError("Malformed token: %r" % old_token)
  803. old_token_name = old_token[len("http://radicale.org/ns/sync/"):]
  804. if not check_token_name(old_token_name):
  805. raise ValueError("Malformed token: %r" % old_token)
  806. # Get the current state and sync-token of the collection.
  807. state = {}
  808. token_name_hash = md5()
  809. # Find the history of all existing and deleted items
  810. for href, item in chain(
  811. ((item.href, item) for item in self.get_all()),
  812. ((href, None) for href in self._get_deleted_history_hrefs())):
  813. history_etag = self._update_history_etag(href, item)
  814. state[href] = history_etag
  815. token_name_hash.update((href + "/" + history_etag).encode("utf-8"))
  816. token_name = token_name_hash.hexdigest()
  817. token = "http://radicale.org/ns/sync/%s" % token_name
  818. if token_name == old_token_name:
  819. # Nothing changed
  820. return token, ()
  821. token_folder = os.path.join(self._filesystem_path,
  822. ".Radicale.cache", "sync-token")
  823. token_path = os.path.join(token_folder, token_name)
  824. old_state = {}
  825. if old_token_name:
  826. # load the old token state
  827. old_token_path = os.path.join(token_folder, old_token_name)
  828. try:
  829. # Race: Another process might have deleted the file.
  830. with open(old_token_path, "rb") as f:
  831. old_state = pickle.load(f)
  832. except (FileNotFoundError, pickle.UnpicklingError,
  833. ValueError) as e:
  834. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  835. self.logger.warning(
  836. "Failed to load stored sync token %r in %r: %s",
  837. old_token_name, self.path, e, exc_info=True)
  838. # Delete the damaged file
  839. try:
  840. os.remove(old_token_path)
  841. except (FileNotFoundError, PermissionError):
  842. pass
  843. raise ValueError("Token not found: %r" % old_token)
  844. # write the new token state or update the modification time of
  845. # existing token state
  846. if not os.path.exists(token_path):
  847. self._makedirs_synced(token_folder)
  848. try:
  849. # Race: Other processes might have created and locked the file.
  850. with self._atomic_write(token_path, "wb") as f:
  851. pickle.dump(state, f)
  852. except PermissionError:
  853. pass
  854. else:
  855. # clean up old sync tokens and item cache
  856. self._clean_cache(token_folder, os.listdir(token_folder),
  857. max_age=self.configuration.getint(
  858. "storage", "max_sync_token_age"))
  859. self._clean_history_cache()
  860. else:
  861. # Try to update the modification time
  862. try:
  863. # Race: Another process might have deleted the file.
  864. os.utime(token_path)
  865. except FileNotFoundError:
  866. pass
  867. changes = []
  868. # Find all new, changed and deleted (that are still in the item cache)
  869. # items
  870. for href, history_etag in state.items():
  871. if history_etag != old_state.get(href):
  872. changes.append(href)
  873. # Find all deleted items that are no longer in the item cache
  874. for href, history_etag in old_state.items():
  875. if href not in state:
  876. changes.append(href)
  877. return token, changes
  878. def list(self):
  879. for href in scandir(self._filesystem_path, only_files=True):
  880. if not is_safe_filesystem_path_component(href):
  881. if not href.startswith(".Radicale"):
  882. self.logger.debug(
  883. "Skipping item %r in %r", href, self.path)
  884. continue
  885. yield href
  886. _item_cache_cleaned = False
  887. def get(self, href, verify_href=True):
  888. item, metadata = self._get_with_metadata(href, verify_href=verify_href)
  889. return item
  890. def _get_with_metadata(self, href, verify_href=True):
  891. """Like ``get`` but additonally returns the following metadata:
  892. tag, start, end: see ``xmlutils.find_tag_and_time_range``. If
  893. extraction of the metadata failed, the values are all ``None``."""
  894. if verify_href:
  895. try:
  896. if not is_safe_filesystem_path_component(href):
  897. raise UnsafePathError(href)
  898. path = path_to_filesystem(self._filesystem_path, href)
  899. except ValueError as e:
  900. self.logger.debug(
  901. "Can't translate name %r safely to filesystem in %r: %s",
  902. href, self.path, e, exc_info=True)
  903. return None, None
  904. else:
  905. path = os.path.join(self._filesystem_path, href)
  906. try:
  907. with open(path, "rb") as f:
  908. btext = f.read()
  909. except (FileNotFoundError, IsADirectoryError):
  910. return None, None
  911. # The hash of the component in the file system. This is used to check,
  912. # if the entry in the cache is still valid.
  913. input_hash = md5()
  914. input_hash.update(self._item_cache_tag)
  915. input_hash.update(btext)
  916. input_hash = input_hash.hexdigest()
  917. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
  918. "item")
  919. cinput_hash = cuid = cetag = ctext = ctag = cstart = cend = None
  920. try:
  921. with open(os.path.join(cache_folder, href), "rb") as f:
  922. cinput_hash, cuid, cetag, ctext, ctag, cstart, cend = \
  923. pickle.load(f)
  924. except FileNotFoundError as e:
  925. pass
  926. except (pickle.UnpicklingError, ValueError) as e:
  927. self.logger.warning(
  928. "Failed to load item cache entry %r in %r: %s",
  929. href, self.path, e, exc_info=True)
  930. vobject_item = None
  931. if input_hash != cinput_hash:
  932. try:
  933. vobject_item = Item(self, href=href,
  934. text=btext.decode(self.encoding)).item
  935. check_and_sanitize_item(vobject_item, uid=cuid)
  936. except Exception as e:
  937. raise RuntimeError("Failed to load item %r in %r: %s" %
  938. (href, self.path, e)) from e
  939. # Serialize the object again, to normalize the text representation.
  940. # The storage may have been edited externally.
  941. ctext = vobject_item.serialize()
  942. cetag = get_etag(ctext)
  943. cuid = get_uid_from_object(vobject_item)
  944. try:
  945. ctag, cstart, cend = xmlutils.find_tag_and_time_range(
  946. vobject_item)
  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