storage.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 sys
  28. import time
  29. from contextlib import contextmanager
  30. from hashlib import md5
  31. from uuid import uuid4
  32. import vobject
  33. from . import config, log
  34. def _load():
  35. """Load the storage manager chosen in configuration."""
  36. storage_type = config.get("storage", "type")
  37. if storage_type == "multifilesystem":
  38. module = sys.modules[__name__]
  39. else:
  40. __import__(storage_type)
  41. module = sys.modules[storage_type]
  42. sys.modules[__name__].Collection = module.Collection
  43. FOLDER = os.path.expanduser(config.get("storage", "filesystem_folder"))
  44. FILESYSTEM_ENCODING = sys.getfilesystemencoding()
  45. STORAGE_ENCODING = config.get("encoding", "stock")
  46. MIMETYPES = {"VADDRESSBOOK": "text/vcard", "VCALENDAR": "text/calendar"}
  47. def get_etag(text):
  48. """Etag from collection or item."""
  49. etag = md5()
  50. etag.update(text.encode("utf-8"))
  51. return '"%s"' % etag.hexdigest()
  52. def sanitize_path(path):
  53. """Make path absolute with leading slash to prevent access to other data.
  54. Preserve a potential trailing slash.
  55. """
  56. trailing_slash = "/" if path.endswith("/") else ""
  57. path = posixpath.normpath(path)
  58. new_path = "/"
  59. for part in path.split("/"):
  60. if not part or part in (".", ".."):
  61. continue
  62. new_path = posixpath.join(new_path, part)
  63. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  64. return new_path + trailing_slash
  65. def is_safe_filesystem_path_component(path):
  66. """Check if path is a single component of a filesystem path.
  67. Check that the path is safe to join too.
  68. """
  69. return (
  70. path and not os.path.splitdrive(path)[0] and
  71. not os.path.split(path)[0] and path not in (os.curdir, os.pardir))
  72. def path_to_filesystem(root, *paths):
  73. """Convert path to a local filesystem path relative to base_folder.
  74. Conversion is done in a secure manner, or raises ``ValueError``.
  75. """
  76. root = sanitize_path(root)
  77. paths = [sanitize_path(path).strip("/") for path in paths]
  78. safe_path = root
  79. for path in paths:
  80. if not path:
  81. continue
  82. for part in path.split("/"):
  83. if not is_safe_filesystem_path_component(part):
  84. log.LOGGER.debug(
  85. "Can't translate path safely to filesystem: %s", path)
  86. raise ValueError("Unsafe path")
  87. safe_path = os.path.join(safe_path, part)
  88. return safe_path
  89. class Item:
  90. def __init__(self, item, href, etag, last_modified=None):
  91. self.item = item
  92. self.href = href
  93. self.etag = etag
  94. self.last_modified = last_modified
  95. def __getattr__(self, attr):
  96. return getattr(self.item, attr)
  97. @property
  98. def content_length(self):
  99. return len(self.serialize().encode(config.get("encoding", "request")))
  100. class Collection:
  101. """Collection stored in several files per calendar."""
  102. def __init__(self, path, principal=False):
  103. """Initialize the collection.
  104. ``path`` must be the normalized relative path of the collection, using
  105. the slash as the folder delimiter, with no leading nor trailing slash.
  106. """
  107. self.encoding = "utf-8"
  108. # path should already be sanitized
  109. self.path = sanitize_path(path).strip("/")
  110. self._filesystem_path = path_to_filesystem(FOLDER, self.path)
  111. split_path = self.path.split("/")
  112. if len(split_path) > 1:
  113. # URL with at least one folder
  114. self.owner = split_path[0]
  115. else:
  116. self.owner = None
  117. self.is_principal = principal
  118. @classmethod
  119. def discover(cls, path, depth="1"):
  120. """Discover a list of collections under the given ``path``.
  121. If ``depth`` is "0", only the actual object under ``path`` is
  122. returned.
  123. If ``depth`` is anything but "0", it is considered as "1" and direct
  124. children are included in the result. If ``include_container`` is
  125. ``True`` (the default), the containing object is included in the
  126. result.
  127. The ``path`` is relative.
  128. """
  129. # path == None means wrong URL
  130. if path is None:
  131. return
  132. # path should already be sanitized
  133. sane_path = sanitize_path(path).strip("/")
  134. attributes = sane_path.split("/")
  135. if not attributes:
  136. return
  137. # Try to guess if the path leads to a collection or an item
  138. if os.path.isfile(path_to_filesystem(FOLDER, sane_path)):
  139. attributes.pop()
  140. path = "/".join(attributes)
  141. principal = len(attributes) <= 1
  142. collection = cls(path, principal)
  143. yield collection
  144. if depth != "0":
  145. # TODO: fix this
  146. items = list(collection.list())
  147. if items:
  148. for item in items:
  149. yield collection.get(item[0])
  150. _, directories, _ = next(os.walk(collection._filesystem_path))
  151. for sub_path in directories:
  152. full_path = os.path.join(collection._filesystem_path, sub_path)
  153. if os.path.exists(path_to_filesystem(full_path)):
  154. yield cls(posixpath.join(path, sub_path))
  155. @classmethod
  156. def create_collection(cls, href, collection=None, tag=None):
  157. """Create a collection.
  158. ``collection`` is a list of vobject components.
  159. ``tag`` is the type of collection (VCALENDAR or VADDRESSBOOK). If
  160. ``tag`` is not given, it is guessed from the collection.
  161. """
  162. path = path_to_filesystem(FOLDER, href)
  163. if not os.path.exists(path):
  164. os.makedirs(path)
  165. if not tag and collection:
  166. tag = collection[0].name
  167. self = cls(href)
  168. if tag == "VCALENDAR":
  169. self.set_meta("tag", "VCALENDAR")
  170. if collection:
  171. collection, = collection
  172. for content in ("vevent", "vtodo", "vjournal"):
  173. if content in collection.contents:
  174. for item in getattr(collection, "%s_list" % content):
  175. new_collection = vobject.iCalendar()
  176. new_collection.add(item)
  177. self.upload(uuid4().hex, new_collection)
  178. elif tag == "VCARD":
  179. self.set_meta("tag", "VADDRESSBOOK")
  180. if collection:
  181. for card in collection:
  182. self.upload(uuid4().hex, card)
  183. return self
  184. def list(self):
  185. """List collection items."""
  186. try:
  187. hrefs = os.listdir(self._filesystem_path)
  188. except IOError:
  189. return
  190. for href in hrefs:
  191. path = os.path.join(self._filesystem_path, href)
  192. if not href.endswith(".props") and os.path.isfile(path):
  193. with open(path, encoding=STORAGE_ENCODING) as fd:
  194. yield href, get_etag(fd.read())
  195. def get(self, href):
  196. """Fetch a single item."""
  197. if not href:
  198. return
  199. href = href.strip("{}").replace("/", "_")
  200. if is_safe_filesystem_path_component(href):
  201. path = os.path.join(self._filesystem_path, href)
  202. if os.path.isfile(path):
  203. with open(path, encoding=STORAGE_ENCODING) as fd:
  204. text = fd.read()
  205. last_modified = time.strftime(
  206. "%a, %d %b %Y %H:%M:%S GMT",
  207. time.gmtime(os.path.getmtime(path)))
  208. return Item(
  209. vobject.readOne(text), href, get_etag(text), last_modified)
  210. else:
  211. log.LOGGER.debug(
  212. "Can't tranlate name safely to filesystem, "
  213. "skipping component: %s", href)
  214. def get_multi(self, hrefs):
  215. """Fetch multiple items. Duplicate hrefs must be ignored.
  216. Functionally similar to ``get``, but might bring performance benefits
  217. on some storages when used cleverly.
  218. """
  219. for href in set(hrefs):
  220. yield self.get(href)
  221. def has(self, href):
  222. """Check if an item exists by its href."""
  223. return self.get(href) is not None
  224. def upload(self, href, item):
  225. """Upload a new item."""
  226. # TODO: use returned object in code
  227. if is_safe_filesystem_path_component(href):
  228. path = path_to_filesystem(self._filesystem_path, href)
  229. if not os.path.exists(path):
  230. text = item.serialize()
  231. with open(path, "w", encoding=STORAGE_ENCODING) as fd:
  232. fd.write(text)
  233. return href, get_etag(text)
  234. else:
  235. log.LOGGER.debug(
  236. "Can't tranlate name safely to filesystem, "
  237. "skipping component: %s", href)
  238. def update(self, href, item, etag=None):
  239. """Update an item."""
  240. # TODO: use etag in code and test it here
  241. # TODO: use returned object in code
  242. if is_safe_filesystem_path_component(href):
  243. path = path_to_filesystem(self._filesystem_path, href)
  244. if os.path.exists(path):
  245. with open(path, encoding=STORAGE_ENCODING) as fd:
  246. text = fd.read()
  247. if not etag or etag == get_etag(text):
  248. new_text = item.serialize()
  249. with open(path, "w", encoding=STORAGE_ENCODING) as fd:
  250. fd.write(new_text)
  251. return get_etag(new_text)
  252. else:
  253. log.LOGGER.debug(
  254. "Can't tranlate name safely to filesystem, "
  255. "skipping component: %s", href)
  256. def delete(self, href=None, etag=None):
  257. """Delete an item.
  258. When ``href`` is ``None``, delete the collection.
  259. """
  260. # TODO: use etag in code and test it here
  261. # TODO: use returned object in code
  262. if href is None:
  263. # Delete the collection
  264. if os.path.isdir(self._filesystem_path):
  265. shutil.rmtree(self._filesystem_path)
  266. props_path = self._filesystem_path + ".props"
  267. if os.path.isfile(props_path):
  268. os.remove(props_path)
  269. return
  270. elif is_safe_filesystem_path_component(href):
  271. # Delete an item
  272. path = path_to_filesystem(self._filesystem_path, href)
  273. if os.path.isfile(path):
  274. with open(path, encoding=STORAGE_ENCODING) as fd:
  275. text = fd.read()
  276. if not etag or etag == get_etag(text):
  277. os.remove(path)
  278. return
  279. else:
  280. log.LOGGER.debug(
  281. "Can't tranlate name safely to filesystem, "
  282. "skipping component: %s", href)
  283. @contextmanager
  284. def at_once(self):
  285. """Set a context manager buffering the reads and writes."""
  286. # TODO: use in code
  287. # TODO: use a file locker
  288. yield
  289. def get_meta(self, key):
  290. """Get metadata value for collection."""
  291. props_path = self._filesystem_path + ".props"
  292. if os.path.exists(props_path):
  293. with open(props_path, encoding=STORAGE_ENCODING) as prop_file:
  294. return json.load(prop_file).get(key)
  295. def set_meta(self, key, value):
  296. """Get metadata value for collection."""
  297. props_path = self._filesystem_path + ".props"
  298. properties = {}
  299. if os.path.exists(props_path):
  300. with open(props_path, encoding=STORAGE_ENCODING) as prop_file:
  301. properties.update(json.load(prop_file))
  302. if value:
  303. properties[key] = value
  304. else:
  305. properties.pop(key, None)
  306. with open(props_path, "w+", encoding=STORAGE_ENCODING) as prop_file:
  307. json.dump(properties, prop_file)
  308. @property
  309. def last_modified(self):
  310. """Get the HTTP-datetime of when the collection was modified."""
  311. last = max([os.path.getmtime(self._filesystem_path)] + [
  312. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  313. for filename in os.listdir(self._filesystem_path)] or [0])
  314. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  315. def serialize(self):
  316. items = []
  317. for href in os.listdir(self._filesystem_path):
  318. path = os.path.join(self._filesystem_path, href)
  319. if os.path.isfile(path) and not path.endswith(".props"):
  320. with open(path, encoding=STORAGE_ENCODING) as fd:
  321. items.append(vobject.readOne(fd.read()))
  322. if self.get_meta("tag") == "VCALENDAR":
  323. collection = vobject.iCalendar()
  324. for item in items:
  325. for content in ("vevent", "vtodo", "vjournal"):
  326. if content in item.contents:
  327. collection.add(getattr(item, content))
  328. break
  329. return collection.serialize()
  330. elif self.get_meta("tag") == "VADDRESSBOOK":
  331. return "".join([item.serialize() for item in items])
  332. return ""
  333. @property
  334. def etag(self):
  335. return get_etag(self.serialize())