storage.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. @property
  101. def etag(self):
  102. return get_etag(self.serialize())
  103. class Collection:
  104. """Collection stored in several files per calendar."""
  105. def __init__(self, path, principal=False):
  106. """Initialize the collection.
  107. ``path`` must be the normalized relative path of the collection, using
  108. the slash as the folder delimiter, with no leading nor trailing slash.
  109. """
  110. self.encoding = "utf-8"
  111. # path should already be sanitized
  112. self.path = sanitize_path(path).strip("/")
  113. self._filesystem_path = path_to_filesystem(FOLDER, self.path)
  114. split_path = self.path.split("/")
  115. if len(split_path) > 1:
  116. # URL with at least one folder
  117. self.owner = split_path[0]
  118. else:
  119. self.owner = None
  120. self.is_principal = principal
  121. @classmethod
  122. def discover(cls, path, depth="1"):
  123. """Discover a list of collections under the given ``path``.
  124. If ``depth`` is "0", only the actual object under ``path`` is
  125. returned.
  126. If ``depth`` is anything but "0", it is considered as "1" and direct
  127. children are included in the result. If ``include_container`` is
  128. ``True`` (the default), the containing object is included in the
  129. result.
  130. The ``path`` is relative.
  131. """
  132. # path == None means wrong URL
  133. if path is None:
  134. return
  135. # path should already be sanitized
  136. sane_path = sanitize_path(path).strip("/")
  137. attributes = sane_path.split("/")
  138. if not attributes:
  139. return
  140. # Try to guess if the path leads to a collection or an item
  141. if not os.path.isdir(path_to_filesystem(FOLDER, sane_path)):
  142. # path is not a collection
  143. if os.path.isfile(path_to_filesystem(FOLDER, sane_path)):
  144. # path is an item
  145. attributes.pop()
  146. elif os.path.isdir(path_to_filesystem(FOLDER, *attributes[:-1])):
  147. # path parent is a collection
  148. attributes.pop()
  149. # TODO: else: return?
  150. path = "/".join(attributes)
  151. principal = len(attributes) <= 1
  152. collection = cls(path, principal)
  153. yield collection
  154. if depth != "0":
  155. # TODO: fix this
  156. items = list(collection.list())
  157. if items:
  158. for item in items:
  159. yield collection.get(item[0])
  160. _, directories, _ = next(os.walk(collection._filesystem_path))
  161. for sub_path in directories:
  162. full_path = os.path.join(collection._filesystem_path, sub_path)
  163. if os.path.exists(path_to_filesystem(full_path)):
  164. yield cls(posixpath.join(path, sub_path))
  165. @classmethod
  166. def create_collection(cls, href, collection=None, tag=None):
  167. """Create a collection.
  168. ``collection`` is a list of vobject components.
  169. ``tag`` is the type of collection (VCALENDAR or VADDRESSBOOK). If
  170. ``tag`` is not given, it is guessed from the collection.
  171. """
  172. path = path_to_filesystem(FOLDER, href)
  173. if not os.path.exists(path):
  174. os.makedirs(path)
  175. if not tag and collection:
  176. tag = collection[0].name
  177. self = cls(href)
  178. if tag == "VCALENDAR":
  179. self.set_meta("tag", "VCALENDAR")
  180. if collection:
  181. collection, = collection
  182. for content in ("vevent", "vtodo", "vjournal"):
  183. if content in collection.contents:
  184. for item in getattr(collection, "%s_list" % content):
  185. new_collection = vobject.iCalendar()
  186. new_collection.add(item)
  187. self.upload(uuid4().hex, new_collection)
  188. elif tag == "VCARD":
  189. self.set_meta("tag", "VADDRESSBOOK")
  190. if collection:
  191. for card in collection:
  192. self.upload(uuid4().hex, card)
  193. return self
  194. def list(self):
  195. """List collection items."""
  196. try:
  197. hrefs = os.listdir(self._filesystem_path)
  198. except IOError:
  199. return
  200. for href in hrefs:
  201. path = os.path.join(self._filesystem_path, href)
  202. if not href.endswith(".props") and os.path.isfile(path):
  203. with open(path, encoding=STORAGE_ENCODING) as fd:
  204. yield href, get_etag(fd.read())
  205. def get(self, href):
  206. """Fetch a single item."""
  207. if not href:
  208. return
  209. href = href.strip("{}").replace("/", "_")
  210. if is_safe_filesystem_path_component(href):
  211. path = os.path.join(self._filesystem_path, href)
  212. if os.path.isfile(path):
  213. with open(path, encoding=STORAGE_ENCODING) as fd:
  214. text = fd.read()
  215. last_modified = time.strftime(
  216. "%a, %d %b %Y %H:%M:%S GMT",
  217. time.gmtime(os.path.getmtime(path)))
  218. return Item(
  219. vobject.readOne(text), href, get_etag(text), last_modified)
  220. else:
  221. log.LOGGER.debug(
  222. "Can't tranlate name safely to filesystem, "
  223. "skipping component: %s", href)
  224. def get_multi(self, hrefs):
  225. """Fetch multiple items. Duplicate hrefs must be ignored.
  226. Functionally similar to ``get``, but might bring performance benefits
  227. on some storages when used cleverly.
  228. """
  229. for href in set(hrefs):
  230. yield self.get(href)
  231. def has(self, href):
  232. """Check if an item exists by its href."""
  233. return self.get(href) is not None
  234. def upload(self, href, item):
  235. """Upload a new item."""
  236. # TODO: use returned object in code
  237. if is_safe_filesystem_path_component(href):
  238. path = path_to_filesystem(self._filesystem_path, href)
  239. if not os.path.exists(path):
  240. text = item.serialize()
  241. with open(path, "w", encoding=STORAGE_ENCODING) as fd:
  242. fd.write(text)
  243. return href, get_etag(text)
  244. else:
  245. log.LOGGER.debug(
  246. "Can't tranlate name safely to filesystem, "
  247. "skipping component: %s", href)
  248. def update(self, href, item, etag=None):
  249. """Update an item."""
  250. # TODO: use etag in code and test it here
  251. # TODO: use returned object in code
  252. if is_safe_filesystem_path_component(href):
  253. path = path_to_filesystem(self._filesystem_path, href)
  254. if os.path.exists(path):
  255. with open(path, encoding=STORAGE_ENCODING) as fd:
  256. text = fd.read()
  257. if not etag or etag == get_etag(text):
  258. new_text = item.serialize()
  259. with open(path, "w", encoding=STORAGE_ENCODING) as fd:
  260. fd.write(new_text)
  261. return get_etag(new_text)
  262. else:
  263. log.LOGGER.debug(
  264. "Can't tranlate name safely to filesystem, "
  265. "skipping component: %s", href)
  266. def delete(self, href=None, etag=None):
  267. """Delete an item.
  268. When ``href`` is ``None``, delete the collection.
  269. """
  270. # TODO: use etag in code and test it here
  271. # TODO: use returned object in code
  272. if href is None:
  273. # Delete the collection
  274. if os.path.isdir(self._filesystem_path):
  275. shutil.rmtree(self._filesystem_path)
  276. props_path = self._filesystem_path + ".props"
  277. if os.path.isfile(props_path):
  278. os.remove(props_path)
  279. return
  280. elif is_safe_filesystem_path_component(href):
  281. # Delete an item
  282. path = path_to_filesystem(self._filesystem_path, href)
  283. if os.path.isfile(path):
  284. with open(path, encoding=STORAGE_ENCODING) as fd:
  285. text = fd.read()
  286. if not etag or etag == get_etag(text):
  287. os.remove(path)
  288. return
  289. else:
  290. log.LOGGER.debug(
  291. "Can't tranlate name safely to filesystem, "
  292. "skipping component: %s", href)
  293. @contextmanager
  294. def at_once(self):
  295. """Set a context manager buffering the reads and writes."""
  296. # TODO: use in code
  297. # TODO: use a file locker
  298. yield
  299. def get_meta(self, key):
  300. """Get metadata value for collection."""
  301. props_path = self._filesystem_path + ".props"
  302. if os.path.exists(props_path):
  303. with open(props_path, encoding=STORAGE_ENCODING) as prop_file:
  304. return json.load(prop_file).get(key)
  305. def set_meta(self, key, value):
  306. """Get metadata value for collection."""
  307. props_path = self._filesystem_path + ".props"
  308. properties = {}
  309. if os.path.exists(props_path):
  310. with open(props_path, encoding=STORAGE_ENCODING) as prop_file:
  311. properties.update(json.load(prop_file))
  312. if value:
  313. properties[key] = value
  314. else:
  315. properties.pop(key, None)
  316. with open(props_path, "w+", encoding=STORAGE_ENCODING) as prop_file:
  317. json.dump(properties, prop_file)
  318. @property
  319. def last_modified(self):
  320. """Get the HTTP-datetime of when the collection was modified."""
  321. last = max([os.path.getmtime(self._filesystem_path)] + [
  322. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  323. for filename in os.listdir(self._filesystem_path)] or [0])
  324. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  325. def serialize(self):
  326. items = []
  327. for href in os.listdir(self._filesystem_path):
  328. path = os.path.join(self._filesystem_path, href)
  329. if os.path.isfile(path) and not path.endswith(".props"):
  330. with open(path, encoding=STORAGE_ENCODING) as fd:
  331. items.append(vobject.readOne(fd.read()))
  332. if self.get_meta("tag") == "VCALENDAR":
  333. collection = vobject.iCalendar()
  334. for item in items:
  335. for content in ("vevent", "vtodo", "vjournal"):
  336. if content in item.contents:
  337. collection.add(getattr(item, content))
  338. break
  339. return collection.serialize()
  340. elif self.get_meta("tag") == "VADDRESSBOOK":
  341. return "".join([item.serialize() for item in items])
  342. return ""
  343. @property
  344. def etag(self):
  345. return get_etag(self.serialize())