__init__.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2014 Jean-Marc Martins
  5. # Copyright © 2008-2017 Guillaume Ayoub
  6. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Module for address books and calendar entries (see ``Item``).
  22. """
  23. import binascii
  24. import math
  25. import os
  26. import sys
  27. from datetime import datetime, timedelta
  28. from hashlib import sha256
  29. from typing import (Any, Callable, List, MutableMapping, Optional, Sequence,
  30. Tuple)
  31. import vobject
  32. from radicale import storage # noqa:F401
  33. from radicale import pathutils
  34. from radicale.item import filter as radicale_filter
  35. from radicale.log import logger
  36. def predict_tag_of_parent_collection(
  37. vobject_items: Sequence[vobject.base.Component]) -> Optional[str]:
  38. """Returns the predicted tag or `None`"""
  39. if len(vobject_items) != 1:
  40. return None
  41. if vobject_items[0].name == "VCALENDAR":
  42. return "VCALENDAR"
  43. if vobject_items[0].name in ("VCARD", "VLIST"):
  44. return "VADDRESSBOOK"
  45. return None
  46. def predict_tag_of_whole_collection(
  47. vobject_items: Sequence[vobject.base.Component],
  48. fallback_tag: Optional[str] = None) -> Optional[str]:
  49. """Returns the predicted tag or `fallback_tag`"""
  50. if vobject_items and vobject_items[0].name == "VCALENDAR":
  51. return "VCALENDAR"
  52. if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
  53. return "VADDRESSBOOK"
  54. if not fallback_tag and not vobject_items:
  55. # Maybe an empty address book
  56. return "VADDRESSBOOK"
  57. return fallback_tag
  58. def check_and_sanitize_items(
  59. vobject_items: List[vobject.base.Component],
  60. is_collection: bool = False, tag: str = "") -> None:
  61. """Check vobject items for common errors and add missing UIDs.
  62. Modifies the list `vobject_items`.
  63. ``is_collection`` indicates that vobject_item contains unrelated
  64. components.
  65. The ``tag`` of the collection.
  66. """
  67. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  68. raise ValueError("Unsupported collection tag: %r" % tag)
  69. if not is_collection and len(vobject_items) != 1:
  70. raise ValueError("Item contains %d components" % len(vobject_items))
  71. if tag == "VCALENDAR":
  72. if len(vobject_items) > 1:
  73. raise RuntimeError("VCALENDAR collection contains %d "
  74. "components" % len(vobject_items))
  75. vobject_item = vobject_items[0]
  76. if vobject_item.name != "VCALENDAR":
  77. raise ValueError("Item type %r not supported in %r "
  78. "collection" % (vobject_item.name, tag))
  79. component_uids = set()
  80. for component in vobject_item.components():
  81. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  82. component_uid = get_uid(component)
  83. if component_uid:
  84. component_uids.add(component_uid)
  85. component_name = None
  86. object_uid = None
  87. object_uid_set = False
  88. for component in vobject_item.components():
  89. # https://tools.ietf.org/html/rfc4791#section-4.1
  90. if component.name == "VTIMEZONE":
  91. continue
  92. if component_name is None or is_collection:
  93. component_name = component.name
  94. elif component_name != component.name:
  95. raise ValueError("Multiple component types in object: %r, %r" %
  96. (component_name, component.name))
  97. if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
  98. continue
  99. component_uid = get_uid(component)
  100. if not object_uid_set or is_collection:
  101. object_uid_set = True
  102. object_uid = component_uid
  103. if not component_uid:
  104. if not is_collection:
  105. raise ValueError("%s component without UID in object" %
  106. component_name)
  107. component_uid = find_available_uid(
  108. component_uids.__contains__)
  109. component_uids.add(component_uid)
  110. if hasattr(component, "uid"):
  111. component.uid.value = component_uid
  112. else:
  113. component.add("UID").value = component_uid
  114. elif not object_uid or not component_uid:
  115. raise ValueError("Multiple %s components without UID in "
  116. "object" % component_name)
  117. elif object_uid != component_uid:
  118. raise ValueError(
  119. "Multiple %s components with different UIDs in object: "
  120. "%r, %r" % (component_name, object_uid, component_uid))
  121. # Workaround for bug in Lightning (Thunderbird)
  122. # Rescheduling a single occurrence from a repeating event creates
  123. # an event with DTEND and DURATION:PT0S
  124. if (hasattr(component, "dtend") and
  125. hasattr(component, "duration") and
  126. component.duration.value == timedelta(0)):
  127. logger.debug("Quirks: Removing zero duration from %s in "
  128. "object %r", component_name, component_uid)
  129. del component.duration
  130. # vobject interprets recurrence rules on demand
  131. try:
  132. component.rruleset
  133. except Exception as e:
  134. raise ValueError("Invalid recurrence rules in %s in object %r"
  135. % (component.name, component_uid)) from e
  136. elif tag == "VADDRESSBOOK":
  137. # https://tools.ietf.org/html/rfc6352#section-5.1
  138. object_uids = set()
  139. for vobject_item in vobject_items:
  140. if vobject_item.name == "VCARD":
  141. object_uid = get_uid(vobject_item)
  142. if object_uid:
  143. object_uids.add(object_uid)
  144. for vobject_item in vobject_items:
  145. if vobject_item.name == "VLIST":
  146. # Custom format used by SOGo Connector to store lists of
  147. # contacts
  148. continue
  149. if vobject_item.name != "VCARD":
  150. raise ValueError("Item type %r not supported in %r "
  151. "collection" % (vobject_item.name, tag))
  152. object_uid = get_uid(vobject_item)
  153. if not object_uid:
  154. if not is_collection:
  155. raise ValueError("%s object without UID" %
  156. vobject_item.name)
  157. object_uid = find_available_uid(object_uids.__contains__)
  158. object_uids.add(object_uid)
  159. if hasattr(vobject_item, "uid"):
  160. vobject_item.uid.value = object_uid
  161. else:
  162. vobject_item.add("UID").value = object_uid
  163. else:
  164. for i in vobject_items:
  165. raise ValueError("Item type %r not supported in %s collection" %
  166. (i.name, repr(tag) if tag else "generic"))
  167. def check_and_sanitize_props(props: MutableMapping[Any, Any]
  168. ) -> MutableMapping[str, str]:
  169. """Check collection properties for common errors.
  170. Modifies the dict `props`.
  171. """
  172. for k, v in list(props.items()): # Make copy to be able to delete items
  173. if not isinstance(k, str):
  174. raise ValueError("Key must be %r not %r: %r" % (
  175. str.__name__, type(k).__name__, k))
  176. if not isinstance(v, str):
  177. if v is None:
  178. del props[k]
  179. continue
  180. raise ValueError("Value of %r must be %r not %r: %r" % (
  181. k, str.__name__, type(v).__name__, v))
  182. if k == "tag":
  183. if v not in ("", "VCALENDAR", "VADDRESSBOOK"):
  184. raise ValueError("Unsupported collection tag: %r" % v)
  185. return props
  186. def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = ""
  187. ) -> str:
  188. """Generate a pseudo-random UID"""
  189. # Prevent infinite loop
  190. for _ in range(1000):
  191. r = binascii.hexlify(os.urandom(16)).decode("ascii")
  192. name = "%s-%s-%s-%s-%s%s" % (
  193. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  194. if not exists_fn(name):
  195. return name
  196. # something is wrong with the PRNG
  197. raise RuntimeError("No unique random sequence found")
  198. def get_etag(text: str) -> str:
  199. """Etag from collection or item.
  200. Encoded as quoted-string (see RFC 2616).
  201. """
  202. etag = sha256()
  203. etag.update(text.encode())
  204. return '"%s"' % etag.hexdigest()
  205. def get_uid(vobject_component: vobject.base.Component) -> str:
  206. """UID value of an item if defined."""
  207. return (vobject_component.uid.value or ""
  208. if hasattr(vobject_component, "uid") else "")
  209. def get_uid_from_object(vobject_item: vobject.base.Component) -> str:
  210. """UID value of an calendar/addressbook object."""
  211. if vobject_item.name == "VCALENDAR":
  212. if hasattr(vobject_item, "vevent"):
  213. return get_uid(vobject_item.vevent)
  214. if hasattr(vobject_item, "vjournal"):
  215. return get_uid(vobject_item.vjournal)
  216. if hasattr(vobject_item, "vtodo"):
  217. return get_uid(vobject_item.vtodo)
  218. elif vobject_item.name == "VCARD":
  219. return get_uid(vobject_item)
  220. return ""
  221. def find_tag(vobject_item: vobject.base.Component) -> str:
  222. """Find component name from ``vobject_item``."""
  223. if vobject_item.name == "VCALENDAR":
  224. for component in vobject_item.components():
  225. if component.name != "VTIMEZONE":
  226. return component.name or ""
  227. return ""
  228. def find_time_range(vobject_item: vobject.base.Component, tag: str
  229. ) -> Tuple[int, int]:
  230. """Find enclosing time range from ``vobject item``.
  231. ``tag`` must be set to the return value of ``find_tag``.
  232. Returns a tuple (``start``, ``end``) where ``start`` and ``end`` are
  233. POSIX timestamps.
  234. This is intened to be used for matching against simplified prefilters.
  235. """
  236. if not tag:
  237. return radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX
  238. start = end = None
  239. def range_fn(range_start: datetime, range_end: datetime,
  240. is_recurrence: bool) -> bool:
  241. nonlocal start, end
  242. if start is None or range_start < start:
  243. start = range_start
  244. if end is None or end < range_end:
  245. end = range_end
  246. return False
  247. def infinity_fn(range_start: datetime) -> bool:
  248. nonlocal start, end
  249. if start is None or range_start < start:
  250. start = range_start
  251. end = radicale_filter.DATETIME_MAX
  252. return True
  253. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  254. if start is None:
  255. start = radicale_filter.DATETIME_MIN
  256. if end is None:
  257. end = radicale_filter.DATETIME_MAX
  258. try:
  259. return math.floor(start.timestamp()), math.ceil(end.timestamp())
  260. except ValueError as e:
  261. if str(e) == ("offset must be a timedelta representing a whole "
  262. "number of minutes") and sys.version_info < (3, 6):
  263. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  264. raise
  265. class Item:
  266. """Class for address book and calendar entries."""
  267. collection: Optional["storage.BaseCollection"]
  268. href: Optional[str]
  269. last_modified: Optional[str]
  270. _collection_path: str
  271. _text: Optional[str]
  272. _vobject_item: Optional[vobject.base.Component]
  273. _etag: Optional[str]
  274. _uid: Optional[str]
  275. _name: Optional[str]
  276. _component_name: Optional[str]
  277. _time_range: Optional[Tuple[int, int]]
  278. def __init__(self,
  279. collection_path: Optional[str] = None,
  280. collection: Optional["storage.BaseCollection"] = None,
  281. vobject_item: Optional[vobject.base.Component] = None,
  282. href: Optional[str] = None,
  283. last_modified: Optional[str] = None,
  284. text: Optional[str] = None,
  285. etag: Optional[str] = None,
  286. uid: Optional[str] = None,
  287. name: Optional[str] = None,
  288. component_name: Optional[str] = None,
  289. time_range: Optional[Tuple[int, int]] = None):
  290. """Initialize an item.
  291. ``collection_path`` the path of the parent collection (optional if
  292. ``collection`` is set).
  293. ``collection`` the parent collection (optional).
  294. ``href`` the href of the item.
  295. ``last_modified`` the HTTP-datetime of when the item was modified.
  296. ``text`` the text representation of the item (optional if
  297. ``vobject_item`` is set).
  298. ``vobject_item`` the vobject item (optional if ``text`` is set).
  299. ``etag`` the etag of the item (optional). See ``get_etag``.
  300. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  301. ``name`` the name of the item (optional). See ``vobject_item.name``.
  302. ``component_name`` the name of the primary component (optional).
  303. See ``find_tag``.
  304. ``time_range`` the enclosing time range. See ``find_time_range``.
  305. """
  306. if text is None and vobject_item is None:
  307. raise ValueError(
  308. "At least one of 'text' or 'vobject_item' must be set")
  309. if collection_path is None:
  310. if collection is None:
  311. raise ValueError("At least one of 'collection_path' or "
  312. "'collection' must be set")
  313. collection_path = collection.path
  314. assert collection_path == pathutils.strip_path(
  315. pathutils.sanitize_path(collection_path))
  316. self._collection_path = collection_path
  317. self.collection = collection
  318. self.href = href
  319. self.last_modified = last_modified
  320. self._text = text
  321. self._vobject_item = vobject_item
  322. self._etag = etag
  323. self._uid = uid
  324. self._name = name
  325. self._component_name = component_name
  326. self._time_range = time_range
  327. def serialize(self) -> str:
  328. if self._text is None:
  329. try:
  330. self._text = self.vobject_item.serialize()
  331. except Exception as e:
  332. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  333. (self.href, self._collection_path,
  334. e)) from e
  335. return self._text
  336. @property
  337. def vobject_item(self):
  338. if self._vobject_item is None:
  339. try:
  340. self._vobject_item = vobject.readOne(self._text)
  341. except Exception as e:
  342. raise RuntimeError("Failed to parse item %r from %r: %s" %
  343. (self.href, self._collection_path,
  344. e)) from e
  345. return self._vobject_item
  346. @property
  347. def etag(self) -> str:
  348. """Encoded as quoted-string (see RFC 2616)."""
  349. if self._etag is None:
  350. self._etag = get_etag(self.serialize())
  351. return self._etag
  352. @property
  353. def uid(self) -> str:
  354. if self._uid is None:
  355. self._uid = get_uid_from_object(self.vobject_item)
  356. return self._uid
  357. @property
  358. def name(self) -> str:
  359. if self._name is None:
  360. self._name = self.vobject_item.name or ""
  361. return self._name
  362. @property
  363. def component_name(self) -> str:
  364. if self._component_name is None:
  365. self._component_name = find_tag(self.vobject_item)
  366. return self._component_name
  367. @property
  368. def time_range(self) -> Tuple[int, int]:
  369. if self._time_range is None:
  370. self._time_range = find_time_range(
  371. self.vobject_item, self.component_name)
  372. return self._time_range
  373. def prepare(self) -> None:
  374. """Fill cache with values."""
  375. orig_vobject_item = self._vobject_item
  376. self.serialize()
  377. self.etag
  378. self.uid
  379. self.name
  380. self.time_range
  381. self.component_name
  382. self._vobject_item = orig_vobject_item