1
0

storage.py 57 KB

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