storage.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2016 Guillaume Ayoub
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. """
  18. Storage backends.
  19. This module loads the storage backend, according to the storage configuration.
  20. Default storage uses one folder per collection and one file per collection
  21. entry.
  22. """
  23. import json
  24. import os
  25. import posixpath
  26. import shutil
  27. import time
  28. from contextlib import contextmanager
  29. from hashlib import md5
  30. from importlib import import_module
  31. from uuid import uuid4
  32. import vobject
  33. def load(configuration, logger):
  34. """Load the storage manager chosen in configuration."""
  35. storage_type = configuration.get("storage", "type")
  36. if storage_type == "multifilesystem":
  37. collection_class = Collection
  38. else:
  39. collection_class = import_module(storage_type).Collection
  40. class CollectionCopy(collection_class):
  41. """Collection copy, avoids overriding the original class attributes."""
  42. CollectionCopy.configuration = configuration
  43. CollectionCopy.logger = logger
  44. return CollectionCopy
  45. MIMETYPES = {"VADDRESSBOOK": "text/vcard", "VCALENDAR": "text/calendar"}
  46. def get_etag(text):
  47. """Etag from collection or item."""
  48. etag = md5()
  49. etag.update(text.encode("utf-8"))
  50. return '"%s"' % etag.hexdigest()
  51. def sanitize_path(path):
  52. """Make path absolute with leading slash to prevent access to other data.
  53. Preserve a potential trailing slash.
  54. """
  55. trailing_slash = "/" if path.endswith("/") else ""
  56. path = posixpath.normpath(path)
  57. new_path = "/"
  58. for part in path.split("/"):
  59. if not part or part in (".", ".."):
  60. continue
  61. new_path = posixpath.join(new_path, part)
  62. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  63. return new_path + trailing_slash
  64. def is_safe_filesystem_path_component(path):
  65. """Check if path is a single component of a filesystem path.
  66. Check that the path is safe to join too.
  67. """
  68. return (
  69. path and not os.path.splitdrive(path)[0] and
  70. not os.path.split(path)[0] and path not in (os.curdir, os.pardir))
  71. def path_to_filesystem(root, *paths):
  72. """Convert path to a local filesystem path relative to base_folder.
  73. Conversion is done in a secure manner, or raises ``ValueError``.
  74. """
  75. paths = [sanitize_path(path).strip("/") for path in paths]
  76. safe_path = root
  77. for path in paths:
  78. if not path:
  79. continue
  80. for part in path.split("/"):
  81. if not is_safe_filesystem_path_component(part):
  82. raise ValueError("Unsafe path")
  83. safe_path = os.path.join(safe_path, part)
  84. return safe_path
  85. class Item:
  86. def __init__(self, collection, item, href, last_modified=None):
  87. self.collection = collection
  88. self.item = item
  89. self.href = href
  90. self.last_modified = last_modified
  91. def __getattr__(self, attr):
  92. return getattr(self.item, attr)
  93. @property
  94. def etag(self):
  95. return get_etag(self.serialize())
  96. class BaseCollection:
  97. # Overriden on copy by the "load" function
  98. configuration = None
  99. logger = None
  100. def __init__(self, path, principal=False):
  101. """Initialize the collection.
  102. ``path`` must be the normalized relative path of the collection, using
  103. the slash as the folder delimiter, with no leading nor trailing slash.
  104. """
  105. raise NotImplementedError
  106. @classmethod
  107. def discover(cls, path, depth="1"):
  108. """Discover a list of collections under the given ``path``.
  109. If ``depth`` is "0", only the actual object under ``path`` is
  110. returned.
  111. If ``depth`` is anything but "0", it is considered as "1" and direct
  112. children are included in the result. If ``include_container`` is
  113. ``True`` (the default), the containing object is included in the
  114. result.
  115. The ``path`` is relative.
  116. """
  117. raise NotImplementedError
  118. @property
  119. def etag(self):
  120. return get_etag(self.serialize())
  121. @classmethod
  122. def create_collection(cls, href, collection=None, tag=None):
  123. """Create a collection.
  124. ``collection`` is a list of vobject components.
  125. ``tag`` is the type of collection (VCALENDAR or VADDRESSBOOK). If
  126. ``tag`` is not given, it is guessed from the collection.
  127. """
  128. raise NotImplementedError
  129. def list(self):
  130. """List collection items."""
  131. raise NotImplementedError
  132. def get(self, href):
  133. """Fetch a single item."""
  134. raise NotImplementedError
  135. def get_multi(self, hrefs):
  136. """Fetch multiple items. Duplicate hrefs must be ignored.
  137. Functionally similar to ``get``, but might bring performance benefits
  138. on some storages when used cleverly.
  139. """
  140. for href in set(hrefs):
  141. yield self.get(href)
  142. def has(self, href):
  143. """Check if an item exists by its href.
  144. Functionally similar to ``get``, but might bring performance benefits
  145. on some storages when used cleverly.
  146. """
  147. return self.get(href) is not None
  148. def upload(self, href, vobject_item):
  149. """Upload a new item."""
  150. raise NotImplementedError
  151. def update(self, href, vobject_item, etag=None):
  152. """Update an item.
  153. Functionally similar to ``delete`` plus ``upload``, but might bring
  154. performance benefits on some storages when used cleverly.
  155. """
  156. self.delete(href, etag)
  157. self.upload(href, vobject_item)
  158. def delete(self, href=None, etag=None):
  159. """Delete an item.
  160. When ``href`` is ``None``, delete the collection.
  161. """
  162. raise NotImplementedError
  163. @contextmanager
  164. def at_once(self):
  165. """Set a context manager buffering the reads and writes."""
  166. # TODO: use in code
  167. yield
  168. def get_meta(self, key):
  169. """Get metadata value for collection."""
  170. raise NotImplementedError
  171. def set_meta(self, key, value):
  172. """Set metadata value for collection."""
  173. raise NotImplementedError
  174. @property
  175. def last_modified(self):
  176. """Get the HTTP-datetime of when the collection was modified."""
  177. raise NotImplementedError
  178. def serialize(self):
  179. """Get the unicode string representing the whole collection."""
  180. raise NotImplementedError
  181. class Collection(BaseCollection):
  182. """Collection stored in several files per calendar."""
  183. def __init__(self, path, principal=False):
  184. folder = os.path.expanduser(
  185. self.configuration.get("storage", "filesystem_folder"))
  186. # path should already be sanitized
  187. self.path = sanitize_path(path).strip("/")
  188. self.storage_encoding = self.configuration.get("encoding", "stock")
  189. self._filesystem_path = path_to_filesystem(folder, self.path)
  190. split_path = self.path.split("/")
  191. if len(split_path) > 1:
  192. # URL with at least one folder
  193. self.owner = split_path[0]
  194. else:
  195. self.owner = None
  196. self.is_principal = principal
  197. @classmethod
  198. def discover(cls, path, depth="1"):
  199. # path == None means wrong URL
  200. if path is None:
  201. return
  202. # path should already be sanitized
  203. sane_path = sanitize_path(path).strip("/")
  204. attributes = sane_path.split("/")
  205. if not attributes:
  206. return
  207. # Try to guess if the path leads to a collection or an item
  208. folder = os.path.expanduser(
  209. cls.configuration.get("storage", "filesystem_folder"))
  210. if not os.path.isdir(path_to_filesystem(folder, sane_path)):
  211. # path is not a collection
  212. if os.path.isfile(path_to_filesystem(folder, sane_path)):
  213. # path is an item
  214. attributes.pop()
  215. elif os.path.isdir(path_to_filesystem(folder, *attributes[:-1])):
  216. # path parent is a collection
  217. attributes.pop()
  218. # TODO: else: return?
  219. path = "/".join(attributes)
  220. principal = len(attributes) <= 1
  221. collection = cls(path, principal)
  222. yield collection
  223. if depth != "0":
  224. # TODO: fix this
  225. items = list(collection.list())
  226. if items:
  227. for item in items:
  228. yield collection.get(item[0])
  229. _, directories, _ = next(os.walk(collection._filesystem_path))
  230. for sub_path in directories:
  231. full_path = os.path.join(collection._filesystem_path, sub_path)
  232. if os.path.exists(full_path):
  233. yield cls(posixpath.join(path, sub_path))
  234. @classmethod
  235. def create_collection(cls, href, collection=None, tag=None):
  236. folder = os.path.expanduser(
  237. cls.configuration.get("storage", "filesystem_folder"))
  238. path = path_to_filesystem(folder, href)
  239. if not os.path.exists(path):
  240. os.makedirs(path)
  241. if not tag and collection:
  242. tag = collection[0].name
  243. self = cls(href)
  244. if tag == "VCALENDAR":
  245. self.set_meta("tag", "VCALENDAR")
  246. if collection:
  247. collection, = collection
  248. for content in ("vevent", "vtodo", "vjournal"):
  249. if content in collection.contents:
  250. for item in getattr(collection, "%s_list" % content):
  251. new_collection = vobject.iCalendar()
  252. new_collection.add(item)
  253. self.upload(uuid4().hex, new_collection)
  254. elif tag == "VCARD":
  255. self.set_meta("tag", "VADDRESSBOOK")
  256. if collection:
  257. for card in collection:
  258. self.upload(uuid4().hex, card)
  259. return self
  260. def list(self):
  261. try:
  262. hrefs = os.listdir(self._filesystem_path)
  263. except IOError:
  264. return
  265. for href in hrefs:
  266. path = os.path.join(self._filesystem_path, href)
  267. if not href.endswith(".props") and os.path.isfile(path):
  268. with open(path, encoding=self.storage_encoding) as fd:
  269. yield href, get_etag(fd.read())
  270. def get(self, href):
  271. if not href:
  272. return
  273. href = href.strip("{}").replace("/", "_")
  274. if is_safe_filesystem_path_component(href):
  275. path = os.path.join(self._filesystem_path, href)
  276. if os.path.isfile(path):
  277. with open(path, encoding=self.storage_encoding) as fd:
  278. text = fd.read()
  279. last_modified = time.strftime(
  280. "%a, %d %b %Y %H:%M:%S GMT",
  281. time.gmtime(os.path.getmtime(path)))
  282. return Item(self, vobject.readOne(text), href, last_modified)
  283. else:
  284. self.logger.debug(
  285. "Can't tranlate name safely to filesystem, "
  286. "skipping component: %s", href)
  287. def has(self, href):
  288. return self.get(href) is not None
  289. def upload(self, href, vobject_item):
  290. # TODO: use returned object in code
  291. if is_safe_filesystem_path_component(href):
  292. path = path_to_filesystem(self._filesystem_path, href)
  293. if not os.path.exists(path):
  294. item = Item(self, vobject_item, href)
  295. with open(path, "w", encoding=self.storage_encoding) as fd:
  296. fd.write(item.serialize())
  297. return item
  298. else:
  299. self.logger.debug(
  300. "Can't tranlate name safely to filesystem, "
  301. "skipping component: %s", href)
  302. def update(self, href, vobject_item, etag=None):
  303. # TODO: use etag in code and test it here
  304. # TODO: use returned object in code
  305. if is_safe_filesystem_path_component(href):
  306. path = path_to_filesystem(self._filesystem_path, href)
  307. if os.path.exists(path):
  308. with open(path, encoding=self.storage_encoding) as fd:
  309. text = fd.read()
  310. if not etag or etag == get_etag(text):
  311. item = Item(self, vobject_item, href)
  312. with open(path, "w", encoding=self.storage_encoding) as fd:
  313. fd.write(item.serialize())
  314. return item
  315. else:
  316. self.logger.debug(
  317. "Can't tranlate name safely to filesystem, "
  318. "skipping component: %s", href)
  319. def delete(self, href=None, etag=None):
  320. # TODO: use etag in code and test it here
  321. # TODO: use returned object in code
  322. if href is None:
  323. # Delete the collection
  324. if os.path.isdir(self._filesystem_path):
  325. shutil.rmtree(self._filesystem_path)
  326. props_path = self._filesystem_path + ".props"
  327. if os.path.isfile(props_path):
  328. os.remove(props_path)
  329. return
  330. elif is_safe_filesystem_path_component(href):
  331. # Delete an item
  332. path = path_to_filesystem(self._filesystem_path, href)
  333. if os.path.isfile(path):
  334. with open(path, encoding=self.storage_encoding) as fd:
  335. text = fd.read()
  336. if not etag or etag == get_etag(text):
  337. os.remove(path)
  338. return
  339. else:
  340. self.logger.debug(
  341. "Can't tranlate name safely to filesystem, "
  342. "skipping component: %s", href)
  343. @contextmanager
  344. def at_once(self):
  345. # TODO: use a file locker
  346. yield
  347. def get_meta(self, key):
  348. props_path = self._filesystem_path + ".props"
  349. if os.path.exists(props_path):
  350. with open(props_path, encoding=self.storage_encoding) as prop:
  351. return json.load(prop).get(key)
  352. def set_meta(self, key, value):
  353. props_path = self._filesystem_path + ".props"
  354. properties = {}
  355. if os.path.exists(props_path):
  356. with open(props_path, encoding=self.storage_encoding) as prop:
  357. properties.update(json.load(prop))
  358. if value:
  359. properties[key] = value
  360. else:
  361. properties.pop(key, None)
  362. with open(props_path, "w+", encoding=self.storage_encoding) as prop:
  363. json.dump(properties, prop)
  364. @property
  365. def last_modified(self):
  366. last = max([os.path.getmtime(self._filesystem_path)] + [
  367. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  368. for filename in os.listdir(self._filesystem_path)] or [0])
  369. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  370. def serialize(self):
  371. items = []
  372. for href in os.listdir(self._filesystem_path):
  373. path = os.path.join(self._filesystem_path, href)
  374. if os.path.isfile(path) and not path.endswith(".props"):
  375. with open(path, encoding=self.storage_encoding) as fd:
  376. items.append(vobject.readOne(fd.read()))
  377. if self.get_meta("tag") == "VCALENDAR":
  378. collection = vobject.iCalendar()
  379. for item in items:
  380. for content in ("vevent", "vtodo", "vjournal"):
  381. if content in item.contents:
  382. collection.add(getattr(item, content))
  383. break
  384. return collection.serialize()
  385. elif self.get_meta("tag") == "VADDRESSBOOK":
  386. return "".join([item.serialize() for item in items])
  387. return ""