storage.py 55 KB

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