__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. # This file is part of Radicale - CalDAV and CardDAV 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 contextlib
  25. import math
  26. import os
  27. import re
  28. from datetime import datetime, timedelta
  29. from hashlib import sha256
  30. from itertools import chain
  31. from typing import (Any, Callable, List, MutableMapping, Optional, Sequence,
  32. Tuple)
  33. import vobject
  34. from radicale import storage # noqa:F401
  35. from radicale import pathutils
  36. from radicale.item import filter as radicale_filter
  37. from radicale.log import logger
  38. def read_components(s: str) -> List[vobject.base.Component]:
  39. """Wrapper for vobject.readComponents"""
  40. # Workaround for bug in InfCloud
  41. # PHOTO is a data URI
  42. s = re.sub(r"^(PHOTO(?:;[^:\r\n]*)?;ENCODING=b(?:;[^:\r\n]*)?:)"
  43. r"data:[^;,\r\n]*;base64,", r"\1", s,
  44. flags=re.MULTILINE | re.IGNORECASE)
  45. # Workaround for bug with malformed ICS files containing control codes
  46. # Filter out all control codes except those we expect to find:
  47. # * 0x09 Horizontal Tab
  48. # * 0x0A Line Feed
  49. # * 0x0D Carriage Return
  50. s = re.sub(r'[\x00-\x08\x0B\x0C\x0E-\x1F]', '', s)
  51. return list(vobject.readComponents(s, allowQP=True))
  52. def predict_tag_of_parent_collection(
  53. vobject_items: Sequence[vobject.base.Component]) -> Optional[str]:
  54. """Returns the predicted tag or `None`"""
  55. if len(vobject_items) != 1:
  56. return None
  57. if vobject_items[0].name == "VCALENDAR":
  58. return "VCALENDAR"
  59. if vobject_items[0].name in ("VCARD", "VLIST"):
  60. return "VADDRESSBOOK"
  61. return None
  62. def predict_tag_of_whole_collection(
  63. vobject_items: Sequence[vobject.base.Component],
  64. fallback_tag: Optional[str] = None) -> Optional[str]:
  65. """Returns the predicted tag or `fallback_tag`"""
  66. if vobject_items and vobject_items[0].name == "VCALENDAR":
  67. return "VCALENDAR"
  68. if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
  69. return "VADDRESSBOOK"
  70. if not fallback_tag and not vobject_items:
  71. # Maybe an empty address book
  72. return "VADDRESSBOOK"
  73. return fallback_tag
  74. def check_and_sanitize_items(
  75. vobject_items: List[vobject.base.Component],
  76. is_collection: bool = False, tag: str = "") -> None:
  77. """Check vobject items for common errors and add missing UIDs.
  78. Modifies the list `vobject_items`.
  79. ``is_collection`` indicates that vobject_item contains unrelated
  80. components.
  81. The ``tag`` of the collection.
  82. """
  83. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK", "VSUBSCRIBED"):
  84. raise ValueError("Unsupported collection tag: %r" % tag)
  85. if not is_collection and len(vobject_items) != 1:
  86. raise ValueError("Item contains %d components" % len(vobject_items))
  87. if tag == "VCALENDAR":
  88. if len(vobject_items) > 1:
  89. raise RuntimeError("VCALENDAR collection contains %d "
  90. "components" % len(vobject_items))
  91. vobject_item = vobject_items[0]
  92. if vobject_item.name != "VCALENDAR":
  93. raise ValueError("Item type %r not supported in %r "
  94. "collection" % (vobject_item.name, tag))
  95. component_uids = set()
  96. for component in vobject_item.components():
  97. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  98. component_uid = get_uid(component)
  99. if component_uid:
  100. component_uids.add(component_uid)
  101. component_name = None
  102. object_uid = None
  103. object_uid_set = False
  104. for component in vobject_item.components():
  105. # https://tools.ietf.org/html/rfc4791#section-4.1
  106. if component.name == "VTIMEZONE":
  107. continue
  108. if component_name is None or is_collection:
  109. component_name = component.name
  110. elif component_name != component.name:
  111. raise ValueError("Multiple component types in object: %r, %r" %
  112. (component_name, component.name))
  113. if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
  114. continue
  115. component_uid = get_uid(component)
  116. if not object_uid_set or is_collection:
  117. object_uid_set = True
  118. object_uid = component_uid
  119. if not component_uid:
  120. if not is_collection:
  121. raise ValueError("%s component without UID in object" %
  122. component_name)
  123. component_uid = find_available_uid(
  124. component_uids.__contains__)
  125. component_uids.add(component_uid)
  126. if hasattr(component, "uid"):
  127. component.uid.value = component_uid
  128. else:
  129. component.add("UID").value = component_uid
  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. "Multiple %s components with different UIDs in object: "
  136. "%r, %r" % (component_name, object_uid, component_uid))
  137. # Workaround for bug in Lightning (Thunderbird)
  138. # Rescheduling a single occurrence from a repeating event creates
  139. # an event with DTEND and DURATION:PT0S
  140. if (hasattr(component, "dtend") and
  141. hasattr(component, "duration") and
  142. component.duration.value == timedelta(0)):
  143. logger.debug("Quirks: Removing zero duration from %s in "
  144. "object %r", component_name, component_uid)
  145. del component.duration
  146. # Workaround for Evolution
  147. # EXDATE has value DATE even if DTSTART/DTEND is DATE-TIME.
  148. # The RFC is vaguely formulated on the issue.
  149. # To resolve the issue convert EXDATE and RDATE to
  150. # the same type as DTDSTART
  151. if hasattr(component, "dtstart"):
  152. ref_date = component.dtstart.value
  153. ref_value_param = component.dtstart.params.get("VALUE")
  154. for dates in chain(component.contents.get("exdate", []),
  155. component.contents.get("rdate", [])):
  156. if all(type(d) is type(ref_date) for d in dates.value):
  157. continue
  158. for i, date in enumerate(dates.value):
  159. dates.value[i] = ref_date.replace(
  160. date.year, date.month, date.day)
  161. with contextlib.suppress(KeyError):
  162. del dates.params["VALUE"]
  163. if ref_value_param is not None:
  164. dates.params["VALUE"] = ref_value_param
  165. # vobject interprets recurrence rules on demand
  166. try:
  167. component.rruleset
  168. except Exception as e:
  169. raise ValueError("Invalid recurrence rules in %s in object %r"
  170. % (component.name, component_uid)) from e
  171. elif tag == "VADDRESSBOOK":
  172. # https://tools.ietf.org/html/rfc6352#section-5.1
  173. object_uids = set()
  174. for vobject_item in vobject_items:
  175. if vobject_item.name == "VCARD":
  176. object_uid = get_uid(vobject_item)
  177. if object_uid:
  178. object_uids.add(object_uid)
  179. for vobject_item in vobject_items:
  180. if vobject_item.name == "VLIST":
  181. # Custom format used by SOGo Connector to store lists of
  182. # contacts
  183. continue
  184. if vobject_item.name != "VCARD":
  185. raise ValueError("Item type %r not supported in %r "
  186. "collection" % (vobject_item.name, tag))
  187. object_uid = get_uid(vobject_item)
  188. if not object_uid:
  189. if not is_collection:
  190. raise ValueError("%s object without UID" %
  191. vobject_item.name)
  192. object_uid = find_available_uid(object_uids.__contains__)
  193. object_uids.add(object_uid)
  194. if hasattr(vobject_item, "uid"):
  195. vobject_item.uid.value = object_uid
  196. else:
  197. vobject_item.add("UID").value = object_uid
  198. else:
  199. for item in vobject_items:
  200. raise ValueError("Item type %r not supported in %s collection" %
  201. (item.name, repr(tag) if tag else "generic"))
  202. def check_and_sanitize_props(props: MutableMapping[Any, Any]
  203. ) -> MutableMapping[str, str]:
  204. """Check collection properties for common errors.
  205. Modifies the dict `props`.
  206. """
  207. for k, v in list(props.items()): # Make copy to be able to delete items
  208. if not isinstance(k, str):
  209. raise ValueError("Key must be %r not %r: %r" % (
  210. str.__name__, type(k).__name__, k))
  211. if not isinstance(v, str):
  212. if v is None:
  213. del props[k]
  214. continue
  215. raise ValueError("Value of %r must be %r not %r: %r" % (
  216. k, str.__name__, type(v).__name__, v))
  217. if k == "tag":
  218. if v not in ("", "VCALENDAR", "VADDRESSBOOK", "VSUBSCRIBED"):
  219. raise ValueError("Unsupported collection tag: %r" % v)
  220. return props
  221. def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = ""
  222. ) -> str:
  223. """Generate a pseudo-random UID"""
  224. # Prevent infinite loop
  225. for _ in range(1000):
  226. r = binascii.hexlify(os.urandom(16)).decode("ascii")
  227. name = "%s-%s-%s-%s-%s%s" % (
  228. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  229. if not exists_fn(name):
  230. return name
  231. # Something is wrong with the PRNG or `exists_fn`
  232. raise RuntimeError("No available random UID found")
  233. def get_etag(text: str) -> str:
  234. """Etag from collection or item.
  235. Encoded as quoted-string (see RFC 2616).
  236. """
  237. etag = sha256()
  238. etag.update(text.encode())
  239. return '"%s"' % etag.hexdigest()
  240. def get_uid(vobject_component: vobject.base.Component) -> str:
  241. """UID value of an item if defined."""
  242. return (vobject_component.uid.value or ""
  243. if hasattr(vobject_component, "uid") else "")
  244. def get_uid_from_object(vobject_item: vobject.base.Component) -> str:
  245. """UID value of an calendar/addressbook object."""
  246. if vobject_item.name == "VCALENDAR":
  247. if hasattr(vobject_item, "vevent"):
  248. return get_uid(vobject_item.vevent)
  249. if hasattr(vobject_item, "vjournal"):
  250. return get_uid(vobject_item.vjournal)
  251. if hasattr(vobject_item, "vtodo"):
  252. return get_uid(vobject_item.vtodo)
  253. elif vobject_item.name == "VCARD":
  254. return get_uid(vobject_item)
  255. return ""
  256. def find_tag(vobject_item: vobject.base.Component) -> str:
  257. """Find component name from ``vobject_item``."""
  258. if vobject_item.name == "VCALENDAR":
  259. for component in vobject_item.components():
  260. if component.name != "VTIMEZONE":
  261. return component.name or ""
  262. return ""
  263. def find_time_range(vobject_item: vobject.base.Component, tag: str
  264. ) -> Tuple[int, int]:
  265. """Find enclosing time range from ``vobject item``.
  266. ``tag`` must be set to the return value of ``find_tag``.
  267. Returns a tuple (``start``, ``end``) where ``start`` and ``end`` are
  268. POSIX timestamps.
  269. This is intended to be used for matching against simplified prefilters.
  270. """
  271. if not tag:
  272. return radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX
  273. start = end = None
  274. def range_fn(range_start: datetime, range_end: datetime,
  275. is_recurrence: bool) -> bool:
  276. nonlocal start, end
  277. if start is None or range_start < start:
  278. start = range_start
  279. if end is None or end < range_end:
  280. end = range_end
  281. return False
  282. def infinity_fn(range_start: datetime) -> bool:
  283. nonlocal start, end
  284. if start is None or range_start < start:
  285. start = range_start
  286. end = radicale_filter.DATETIME_MAX
  287. return True
  288. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  289. if start is None:
  290. start = radicale_filter.DATETIME_MIN
  291. if end is None:
  292. end = radicale_filter.DATETIME_MAX
  293. return math.floor(start.timestamp()), math.ceil(end.timestamp())
  294. class Item:
  295. """Class for address book and calendar entries."""
  296. collection: Optional["storage.BaseCollection"]
  297. href: Optional[str]
  298. last_modified: Optional[str]
  299. _collection_path: str
  300. _text: Optional[str]
  301. _vobject_item: Optional[vobject.base.Component]
  302. _etag: Optional[str]
  303. _uid: Optional[str]
  304. _name: Optional[str]
  305. _component_name: Optional[str]
  306. _time_range: Optional[Tuple[int, int]]
  307. def __init__(self,
  308. collection_path: Optional[str] = None,
  309. collection: Optional["storage.BaseCollection"] = None,
  310. vobject_item: Optional[vobject.base.Component] = None,
  311. href: Optional[str] = None,
  312. last_modified: Optional[str] = None,
  313. text: Optional[str] = None,
  314. etag: Optional[str] = None,
  315. uid: Optional[str] = None,
  316. name: Optional[str] = None,
  317. component_name: Optional[str] = None,
  318. time_range: Optional[Tuple[int, int]] = None):
  319. """Initialize an item.
  320. ``collection_path`` the path of the parent collection (optional if
  321. ``collection`` is set).
  322. ``collection`` the parent collection (optional).
  323. ``href`` the href of the item.
  324. ``last_modified`` the HTTP-datetime of when the item was modified.
  325. ``text`` the text representation of the item (optional if
  326. ``vobject_item`` is set).
  327. ``vobject_item`` the vobject item (optional if ``text`` is set).
  328. ``etag`` the etag of the item (optional). See ``get_etag``.
  329. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  330. ``name`` the name of the item (optional). See ``vobject_item.name``.
  331. ``component_name`` the name of the primary component (optional).
  332. See ``find_tag``.
  333. ``time_range`` the enclosing time range. See ``find_time_range``.
  334. """
  335. if text is None and vobject_item is None:
  336. raise ValueError(
  337. "At least one of 'text' or 'vobject_item' must be set")
  338. if collection_path is None:
  339. if collection is None:
  340. raise ValueError("At least one of 'collection_path' or "
  341. "'collection' must be set")
  342. collection_path = collection.path
  343. assert collection_path == pathutils.strip_path(
  344. pathutils.sanitize_path(collection_path))
  345. self._collection_path = collection_path
  346. self.collection = collection
  347. self.href = href
  348. self.last_modified = last_modified
  349. self._text = text
  350. self._vobject_item = vobject_item
  351. self._etag = etag
  352. self._uid = uid
  353. self._name = name
  354. self._component_name = component_name
  355. self._time_range = time_range
  356. def serialize(self) -> str:
  357. if self._text is None:
  358. try:
  359. self._text = self.vobject_item.serialize()
  360. except Exception as e:
  361. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  362. (self.href, self._collection_path,
  363. e)) from e
  364. return self._text
  365. @property
  366. def vobject_item(self):
  367. if self._vobject_item is None:
  368. try:
  369. self._vobject_item = vobject.readOne(self._text)
  370. except Exception as e:
  371. raise RuntimeError("Failed to parse item %r from %r: %s" %
  372. (self.href, self._collection_path,
  373. e)) from e
  374. return self._vobject_item
  375. @property
  376. def etag(self) -> str:
  377. """Encoded as quoted-string (see RFC 2616)."""
  378. if self._etag is None:
  379. self._etag = get_etag(self.serialize())
  380. return self._etag
  381. @property
  382. def uid(self) -> str:
  383. if self._uid is None:
  384. self._uid = get_uid_from_object(self.vobject_item)
  385. return self._uid
  386. @property
  387. def name(self) -> str:
  388. if self._name is None:
  389. self._name = self.vobject_item.name or ""
  390. return self._name
  391. @property
  392. def component_name(self) -> str:
  393. if self._component_name is None:
  394. self._component_name = find_tag(self.vobject_item)
  395. return self._component_name
  396. @property
  397. def time_range(self) -> Tuple[int, int]:
  398. if self._time_range is None:
  399. self._time_range = find_time_range(
  400. self.vobject_item, self.component_name)
  401. return self._time_range
  402. def prepare(self) -> None:
  403. """Fill cache with values."""
  404. orig_vobject_item = self._vobject_item
  405. self.serialize()
  406. self.etag
  407. self.uid
  408. self.name
  409. self.time_range
  410. self.component_name
  411. self._vobject_item = orig_vobject_item