__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 in object %r"
  124. % (component.name, component_uid)) 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. for k, v in props.copy().items(): # Make copy to be able to delete items
  159. if not isinstance(k, str):
  160. raise ValueError("Key must be %r not %r: %r" % (
  161. str.__name__, type(k).__name__, k))
  162. if not isinstance(v, str):
  163. if v is None:
  164. del props[k]
  165. continue
  166. raise ValueError("Value of %r must be %r not %r: %r" % (
  167. k, str.__name__, type(v).__name__, v))
  168. if k == "tag":
  169. if not v:
  170. del props[k]
  171. continue
  172. if v not in ("VCALENDAR", "VADDRESSBOOK"):
  173. raise ValueError("Unsupported collection tag: %r" % v)
  174. def find_available_uid(exists_fn, suffix=""):
  175. """Generate a pseudo-random UID"""
  176. # Prevent infinite loop
  177. for _ in range(1000):
  178. r = binascii.hexlify(os.urandom(16)).decode("ascii")
  179. name = "%s-%s-%s-%s-%s%s" % (
  180. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  181. if not exists_fn(name):
  182. return name
  183. # something is wrong with the PRNG
  184. raise RuntimeError("No unique random sequence found")
  185. def get_etag(text):
  186. """Etag from collection or item.
  187. Encoded as quoted-string (see RFC 2616).
  188. """
  189. etag = sha256()
  190. etag.update(text.encode())
  191. return '"%s"' % etag.hexdigest()
  192. def get_uid(vobject_component):
  193. """UID value of an item if defined."""
  194. return (vobject_component.uid.value
  195. if hasattr(vobject_component, "uid") else None)
  196. def get_uid_from_object(vobject_item):
  197. """UID value of an calendar/addressbook object."""
  198. if vobject_item.name == "VCALENDAR":
  199. if hasattr(vobject_item, "vevent"):
  200. return get_uid(vobject_item.vevent)
  201. if hasattr(vobject_item, "vjournal"):
  202. return get_uid(vobject_item.vjournal)
  203. if hasattr(vobject_item, "vtodo"):
  204. return get_uid(vobject_item.vtodo)
  205. elif vobject_item.name == "VCARD":
  206. return get_uid(vobject_item)
  207. return None
  208. def find_tag(vobject_item):
  209. """Find component name from ``vobject_item``."""
  210. if vobject_item.name == "VCALENDAR":
  211. for component in vobject_item.components():
  212. if component.name != "VTIMEZONE":
  213. return component.name or ""
  214. return ""
  215. def find_tag_and_time_range(vobject_item):
  216. """Find component name and enclosing time range from ``vobject item``.
  217. Returns a tuple (``tag``, ``start``, ``end``) where ``tag`` is a string
  218. and ``start`` and ``end`` are POSIX timestamps (as int).
  219. This is intened to be used for matching against simplified prefilters.
  220. """
  221. tag = find_tag(vobject_item)
  222. if not tag:
  223. return (
  224. tag, radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX)
  225. start = end = None
  226. def range_fn(range_start, range_end, is_recurrence):
  227. nonlocal start, end
  228. if start is None or range_start < start:
  229. start = range_start
  230. if end is None or end < range_end:
  231. end = range_end
  232. return False
  233. def infinity_fn(range_start):
  234. nonlocal start, end
  235. if start is None or range_start < start:
  236. start = range_start
  237. end = radicale_filter.DATETIME_MAX
  238. return True
  239. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  240. if start is None:
  241. start = radicale_filter.DATETIME_MIN
  242. if end is None:
  243. end = radicale_filter.DATETIME_MAX
  244. try:
  245. return tag, math.floor(start.timestamp()), math.ceil(end.timestamp())
  246. except ValueError as e:
  247. if str(e) == ("offset must be a timedelta representing a whole "
  248. "number of minutes") and sys.version_info < (3, 6):
  249. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  250. raise
  251. class Item:
  252. """Class for address book and calendar entries."""
  253. def __init__(self, collection_path=None, collection=None,
  254. vobject_item=None, href=None, last_modified=None, text=None,
  255. etag=None, uid=None, name=None, component_name=None,
  256. time_range=None):
  257. """Initialize an item.
  258. ``collection_path`` the path of the parent collection (optional if
  259. ``collection`` is set).
  260. ``collection`` the parent collection (optional).
  261. ``href`` the href of the item.
  262. ``last_modified`` the HTTP-datetime of when the item was modified.
  263. ``text`` the text representation of the item (optional if
  264. ``vobject_item`` is set).
  265. ``vobject_item`` the vobject item (optional if ``text`` is set).
  266. ``etag`` the etag of the item (optional). See ``get_etag``.
  267. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  268. ``name`` the name of the item (optional). See ``vobject_item.name``.
  269. ``component_name`` the name of the primary component (optional).
  270. See ``find_tag``.
  271. ``time_range`` the enclosing time range.
  272. See ``find_tag_and_time_range``.
  273. """
  274. if text is None and vobject_item is None:
  275. raise ValueError(
  276. "At least one of 'text' or 'vobject_item' must be set")
  277. if collection_path is None:
  278. if collection is None:
  279. raise ValueError("At least one of 'collection_path' or "
  280. "'collection' must be set")
  281. collection_path = collection.path
  282. assert collection_path == pathutils.strip_path(
  283. pathutils.sanitize_path(collection_path))
  284. self._collection_path = collection_path
  285. self.collection = collection
  286. self.href = href
  287. self.last_modified = last_modified
  288. self._text = text
  289. self._vobject_item = vobject_item
  290. self._etag = etag
  291. self._uid = uid
  292. self._name = name
  293. self._component_name = component_name
  294. self._time_range = time_range
  295. def serialize(self):
  296. if self._text is None:
  297. try:
  298. self._text = self.vobject_item.serialize()
  299. except Exception as e:
  300. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  301. (self.href, self._collection_path,
  302. e)) from e
  303. return self._text
  304. @property
  305. def vobject_item(self):
  306. if self._vobject_item is None:
  307. try:
  308. self._vobject_item = vobject.readOne(self._text)
  309. except Exception as e:
  310. raise RuntimeError("Failed to parse item %r from %r: %s" %
  311. (self.href, self._collection_path,
  312. e)) from e
  313. return self._vobject_item
  314. @property
  315. def etag(self):
  316. """Encoded as quoted-string (see RFC 2616)."""
  317. if self._etag is None:
  318. self._etag = get_etag(self.serialize())
  319. return self._etag
  320. @property
  321. def uid(self):
  322. if self._uid is None:
  323. self._uid = get_uid_from_object(self.vobject_item)
  324. return self._uid
  325. @property
  326. def name(self):
  327. if self._name is None:
  328. self._name = self.vobject_item.name or ""
  329. return self._name
  330. @property
  331. def component_name(self):
  332. if self._component_name is not None:
  333. return self._component_name
  334. return find_tag(self.vobject_item)
  335. @property
  336. def time_range(self):
  337. if self._time_range is None:
  338. self._component_name, *self._time_range = (
  339. find_tag_and_time_range(self.vobject_item))
  340. return self._time_range
  341. def prepare(self):
  342. """Fill cache with values."""
  343. orig_vobject_item = self._vobject_item
  344. self.serialize()
  345. self.etag
  346. self.uid
  347. self.name
  348. self.time_range
  349. self.component_name
  350. self._vobject_item = orig_vobject_item