__init__.py 14 KB

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