__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 timedelta
  28. from hashlib import sha256
  29. import vobject
  30. from radicale import pathutils
  31. from radicale.item import filter as radicale_filter
  32. from radicale.log import logger
  33. def predict_tag_of_parent_collection(vobject_items):
  34. if len(vobject_items) != 1:
  35. return ""
  36. if vobject_items[0].name == "VCALENDAR":
  37. return "VCALENDAR"
  38. if vobject_items[0].name in ("VCARD", "VLIST"):
  39. return "VADDRESSBOOK"
  40. return ""
  41. def predict_tag_of_whole_collection(vobject_items, fallback_tag=None):
  42. if vobject_items and vobject_items[0].name == "VCALENDAR":
  43. return "VCALENDAR"
  44. if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
  45. return "VADDRESSBOOK"
  46. if not fallback_tag and not vobject_items:
  47. # Maybe an empty address book
  48. return "VADDRESSBOOK"
  49. return fallback_tag
  50. def check_and_sanitize_items(vobject_items, is_collection=False, tag=None):
  51. """Check vobject items for common errors and add missing UIDs.
  52. ``is_collection`` indicates that vobject_item contains unrelated
  53. components.
  54. The ``tag`` of the collection.
  55. """
  56. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  57. raise ValueError("Unsupported collection tag: %r" % tag)
  58. if not is_collection and len(vobject_items) != 1:
  59. raise ValueError("Item contains %d components" % len(vobject_items))
  60. if tag == "VCALENDAR":
  61. if len(vobject_items) > 1:
  62. raise RuntimeError("VCALENDAR collection contains %d "
  63. "components" % len(vobject_items))
  64. vobject_item = vobject_items[0]
  65. if vobject_item.name != "VCALENDAR":
  66. raise ValueError("Item type %r not supported in %r "
  67. "collection" % (vobject_item.name, tag))
  68. component_uids = set()
  69. for component in vobject_item.components():
  70. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  71. component_uid = get_uid(component)
  72. if component_uid:
  73. component_uids.add(component_uid)
  74. component_name = None
  75. object_uid = None
  76. object_uid_set = False
  77. for component in vobject_item.components():
  78. # https://tools.ietf.org/html/rfc4791#section-4.1
  79. if component.name == "VTIMEZONE":
  80. continue
  81. if component_name is None or is_collection:
  82. component_name = component.name
  83. elif component_name != component.name:
  84. raise ValueError("Multiple component types in object: %r, %r" %
  85. (component_name, component.name))
  86. if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
  87. continue
  88. component_uid = get_uid(component)
  89. if not object_uid_set or is_collection:
  90. object_uid_set = True
  91. object_uid = component_uid
  92. if not component_uid:
  93. if not is_collection:
  94. raise ValueError("%s component without UID in object" %
  95. component_name)
  96. component_uid = find_available_uid(
  97. component_uids.__contains__)
  98. component_uids.add(component_uid)
  99. if hasattr(component, "uid"):
  100. component.uid.value = component_uid
  101. else:
  102. component.add("UID").value = component_uid
  103. elif not object_uid or not component_uid:
  104. raise ValueError("Multiple %s components without UID in "
  105. "object" % component_name)
  106. elif object_uid != component_uid:
  107. raise ValueError(
  108. "Multiple %s components with different UIDs in object: "
  109. "%r, %r" % (component_name, object_uid, component_uid))
  110. # Workaround for bug in Lightning (Thunderbird)
  111. # Rescheduling a single occurrence from a repeating event creates
  112. # an event with DTEND and DURATION:PT0S
  113. if (hasattr(component, "dtend") and
  114. hasattr(component, "duration") and
  115. component.duration.value == timedelta(0)):
  116. logger.debug("Quirks: Removing zero duration from %s in "
  117. "object %r", component_name, component_uid)
  118. del component.duration
  119. # vobject interprets recurrence rules on demand
  120. try:
  121. component.rruleset
  122. except Exception as e:
  123. raise ValueError("invalid recurrence rules in %s" %
  124. component.name) from e
  125. elif tag == "VADDRESSBOOK":
  126. # https://tools.ietf.org/html/rfc6352#section-5.1
  127. object_uids = set()
  128. for vobject_item in vobject_items:
  129. if vobject_item.name == "VCARD":
  130. object_uid = get_uid(vobject_item)
  131. if object_uid:
  132. object_uids.add(object_uid)
  133. for vobject_item in vobject_items:
  134. if vobject_item.name == "VLIST":
  135. # Custom format used by SOGo Connector to store lists of
  136. # contacts
  137. continue
  138. if vobject_item.name != "VCARD":
  139. raise ValueError("Item type %r not supported in %r "
  140. "collection" % (vobject_item.name, tag))
  141. object_uid = get_uid(vobject_item)
  142. if not object_uid:
  143. if not is_collection:
  144. raise ValueError("%s object without UID" %
  145. vobject_item.name)
  146. object_uid = find_available_uid(object_uids.__contains__)
  147. object_uids.add(object_uid)
  148. if hasattr(vobject_item, "uid"):
  149. vobject_item.uid.value = object_uid
  150. else:
  151. vobject_item.add("UID").value = object_uid
  152. else:
  153. for i in vobject_items:
  154. raise ValueError("Item type %r not supported in %s collection" %
  155. (i.name, repr(tag) if tag else "generic"))
  156. def check_and_sanitize_props(props):
  157. """Check collection properties for common errors."""
  158. tag = props.get("tag")
  159. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  160. raise ValueError("Unsupported collection tag: %r" % tag)
  161. def find_available_uid(exists_fn, suffix=""):
  162. """Generate a pseudo-random UID"""
  163. # Prevent infinite loop
  164. for _ in range(1000):
  165. r = binascii.hexlify(os.urandom(16)).decode("ascii")
  166. name = "%s-%s-%s-%s-%s%s" % (
  167. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  168. if not exists_fn(name):
  169. return name
  170. # something is wrong with the PRNG
  171. raise RuntimeError("No unique random sequence found")
  172. def get_etag(text):
  173. """Etag from collection or item.
  174. Encoded as quoted-string (see RFC 2616).
  175. """
  176. etag = sha256()
  177. etag.update(text.encode())
  178. return '"%s"' % etag.hexdigest()
  179. def get_uid(vobject_component):
  180. """UID value of an item if defined."""
  181. return (vobject_component.uid.value
  182. if hasattr(vobject_component, "uid") else None)
  183. def get_uid_from_object(vobject_item):
  184. """UID value of an calendar/addressbook object."""
  185. if vobject_item.name == "VCALENDAR":
  186. if hasattr(vobject_item, "vevent"):
  187. return get_uid(vobject_item.vevent)
  188. if hasattr(vobject_item, "vjournal"):
  189. return get_uid(vobject_item.vjournal)
  190. if hasattr(vobject_item, "vtodo"):
  191. return get_uid(vobject_item.vtodo)
  192. elif vobject_item.name == "VCARD":
  193. return get_uid(vobject_item)
  194. return None
  195. def find_tag(vobject_item):
  196. """Find component name from ``vobject_item``."""
  197. if vobject_item.name == "VCALENDAR":
  198. for component in vobject_item.components():
  199. if component.name != "VTIMEZONE":
  200. return component.name or ""
  201. return ""
  202. def find_tag_and_time_range(vobject_item):
  203. """Find component name and enclosing time range from ``vobject item``.
  204. Returns a tuple (``tag``, ``start``, ``end``) where ``tag`` is a string
  205. and ``start`` and ``end`` are POSIX timestamps (as int).
  206. This is intened to be used for matching against simplified prefilters.
  207. """
  208. tag = find_tag(vobject_item)
  209. if not tag:
  210. return (
  211. tag, radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX)
  212. start = end = None
  213. def range_fn(range_start, range_end, is_recurrence):
  214. nonlocal start, end
  215. if start is None or range_start < start:
  216. start = range_start
  217. if end is None or end < range_end:
  218. end = range_end
  219. return False
  220. def infinity_fn(range_start):
  221. nonlocal start, end
  222. if start is None or range_start < start:
  223. start = range_start
  224. end = radicale_filter.DATETIME_MAX
  225. return True
  226. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  227. if start is None:
  228. start = radicale_filter.DATETIME_MIN
  229. if end is None:
  230. end = radicale_filter.DATETIME_MAX
  231. try:
  232. return tag, math.floor(start.timestamp()), math.ceil(end.timestamp())
  233. except ValueError as e:
  234. if str(e) == ("offset must be a timedelta representing a whole "
  235. "number of minutes") and sys.version_info < (3, 6):
  236. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  237. raise
  238. class Item:
  239. """Class for address book and calendar entries."""
  240. def __init__(self, collection_path=None, collection=None,
  241. vobject_item=None, href=None, last_modified=None, text=None,
  242. etag=None, uid=None, name=None, component_name=None,
  243. time_range=None):
  244. """Initialize an item.
  245. ``collection_path`` the path of the parent collection (optional if
  246. ``collection`` is set).
  247. ``collection`` the parent collection (optional).
  248. ``href`` the href of the item.
  249. ``last_modified`` the HTTP-datetime of when the item was modified.
  250. ``text`` the text representation of the item (optional if
  251. ``vobject_item`` is set).
  252. ``vobject_item`` the vobject item (optional if ``text`` is set).
  253. ``etag`` the etag of the item (optional). See ``get_etag``.
  254. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  255. ``name`` the name of the item (optional). See ``vobject_item.name``.
  256. ``component_name`` the name of the primary component (optional).
  257. See ``find_tag``.
  258. ``time_range`` the enclosing time range.
  259. See ``find_tag_and_time_range``.
  260. """
  261. if text is None and vobject_item is None:
  262. raise ValueError(
  263. "at least one of 'text' or 'vobject_item' must be set")
  264. if collection_path is None:
  265. if collection is None:
  266. raise ValueError("at least one of 'collection_path' or "
  267. "'collection' must be set")
  268. collection_path = collection.path
  269. assert collection_path == pathutils.strip_path(
  270. pathutils.sanitize_path(collection_path))
  271. self._collection_path = collection_path
  272. self.collection = collection
  273. self.href = href
  274. self.last_modified = last_modified
  275. self._text = text
  276. self._vobject_item = vobject_item
  277. self._etag = etag
  278. self._uid = uid
  279. self._name = name
  280. self._component_name = component_name
  281. self._time_range = time_range
  282. def serialize(self):
  283. if self._text is None:
  284. try:
  285. self._text = self.vobject_item.serialize()
  286. except Exception as e:
  287. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  288. (self.href, self._collection_path,
  289. e)) from e
  290. return self._text
  291. @property
  292. def vobject_item(self):
  293. if self._vobject_item is None:
  294. try:
  295. self._vobject_item = vobject.readOne(self._text)
  296. except Exception as e:
  297. raise RuntimeError("Failed to parse item %r from %r: %s" %
  298. (self.href, self._collection_path,
  299. e)) from e
  300. return self._vobject_item
  301. @property
  302. def etag(self):
  303. """Encoded as quoted-string (see RFC 2616)."""
  304. if self._etag is None:
  305. self._etag = get_etag(self.serialize())
  306. return self._etag
  307. @property
  308. def uid(self):
  309. if self._uid is None:
  310. self._uid = get_uid_from_object(self.vobject_item)
  311. return self._uid
  312. @property
  313. def name(self):
  314. if self._name is None:
  315. self._name = self.vobject_item.name or ""
  316. return self._name
  317. @property
  318. def component_name(self):
  319. if self._component_name is not None:
  320. return self._component_name
  321. return find_tag(self.vobject_item)
  322. @property
  323. def time_range(self):
  324. if self._time_range is None:
  325. self._component_name, *self._time_range = (
  326. find_tag_and_time_range(self.vobject_item))
  327. return self._time_range
  328. def prepare(self):
  329. """Fill cache with values."""
  330. orig_vobject_item = self._vobject_item
  331. self.serialize()
  332. self.etag
  333. self.uid
  334. self.name
  335. self.time_range
  336. self.component_name
  337. self._vobject_item = orig_vobject_item