storage.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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 stat
  28. import threading
  29. import time
  30. from contextlib import contextmanager
  31. from hashlib import md5
  32. from importlib import import_module
  33. from uuid import uuid4
  34. import vobject
  35. if os.name == "nt":
  36. import ctypes
  37. import ctypes.wintypes
  38. import msvcrt
  39. LOCKFILE_EXCLUSIVE_LOCK = 2
  40. if ctypes.sizeof(ctypes.c_void_p) == 4:
  41. ULONG_PTR = ctypes.c_uint32
  42. else:
  43. ULONG_PTR = ctypes.c_uint64
  44. class Overlapped(ctypes.Structure):
  45. _fields_ = [("internal", ULONG_PTR),
  46. ("internal_high", ULONG_PTR),
  47. ("offset", ctypes.wintypes.DWORD),
  48. ("offset_high", ctypes.wintypes.DWORD),
  49. ("h_event", ctypes.wintypes.HANDLE)]
  50. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  51. lock_file_ex.argtypes = [ctypes.wintypes.HANDLE,
  52. ctypes.wintypes.DWORD,
  53. ctypes.wintypes.DWORD,
  54. ctypes.wintypes.DWORD,
  55. ctypes.wintypes.DWORD,
  56. ctypes.POINTER(Overlapped)]
  57. lock_file_ex.restype = ctypes.wintypes.BOOL
  58. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  59. unlock_file_ex.argtypes = [ctypes.wintypes.HANDLE,
  60. ctypes.wintypes.DWORD,
  61. ctypes.wintypes.DWORD,
  62. ctypes.wintypes.DWORD,
  63. ctypes.POINTER(Overlapped)]
  64. unlock_file_ex.restype = ctypes.wintypes.BOOL
  65. elif os.name == "posix":
  66. import fcntl
  67. def load(configuration, logger):
  68. """Load the storage manager chosen in configuration."""
  69. storage_type = configuration.get("storage", "type")
  70. if storage_type == "multifilesystem":
  71. collection_class = Collection
  72. else:
  73. collection_class = import_module(storage_type).Collection
  74. class CollectionCopy(collection_class):
  75. """Collection copy, avoids overriding the original class attributes."""
  76. CollectionCopy.configuration = configuration
  77. CollectionCopy.logger = logger
  78. return CollectionCopy
  79. MIMETYPES = {"VADDRESSBOOK": "text/vcard", "VCALENDAR": "text/calendar"}
  80. def get_etag(text):
  81. """Etag from collection or item."""
  82. etag = md5()
  83. etag.update(text.encode("utf-8"))
  84. return '"%s"' % etag.hexdigest()
  85. def sanitize_path(path):
  86. """Make path absolute with leading slash to prevent access to other data.
  87. Preserve a potential trailing slash.
  88. """
  89. trailing_slash = "/" if path.endswith("/") else ""
  90. path = posixpath.normpath(path)
  91. new_path = "/"
  92. for part in path.split("/"):
  93. if not part or part in (".", ".."):
  94. continue
  95. new_path = posixpath.join(new_path, part)
  96. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  97. return new_path + trailing_slash
  98. def is_safe_filesystem_path_component(path):
  99. """Check if path is a single component of a filesystem path.
  100. Check that the path is safe to join too.
  101. """
  102. return (
  103. path and not os.path.splitdrive(path)[0] and
  104. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  105. not path.startswith(".") and not path.endswith("~"))
  106. def path_to_filesystem(root, *paths):
  107. """Convert path to a local filesystem path relative to base_folder.
  108. `root` must be a secure filesystem path, it will be prepend to the path.
  109. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  110. """
  111. paths = [sanitize_path(path).strip("/") for path in paths]
  112. safe_path = root
  113. for path in paths:
  114. if not path:
  115. continue
  116. for part in path.split("/"):
  117. if not is_safe_filesystem_path_component(part):
  118. raise ValueError("Unsafe path")
  119. safe_path = os.path.join(safe_path, part)
  120. return safe_path
  121. class Item:
  122. def __init__(self, collection, item, href, last_modified=None):
  123. self.collection = collection
  124. self.item = item
  125. self.href = href
  126. self.last_modified = last_modified
  127. def __getattr__(self, attr):
  128. return getattr(self.item, attr)
  129. @property
  130. def etag(self):
  131. return get_etag(self.serialize())
  132. class BaseCollection:
  133. # Overriden on copy by the "load" function
  134. configuration = None
  135. logger = None
  136. def __init__(self, path, principal=False):
  137. """Initialize the collection.
  138. ``path`` must be the normalized relative path of the collection, using
  139. the slash as the folder delimiter, with no leading nor trailing slash.
  140. """
  141. raise NotImplementedError
  142. @classmethod
  143. def discover(cls, path, depth="1"):
  144. """Discover a list of collections under the given ``path``.
  145. If ``depth`` is "0", only the actual object under ``path`` is
  146. returned.
  147. If ``depth`` is anything but "0", it is considered as "1" and direct
  148. children are included in the result. If ``include_container`` is
  149. ``True`` (the default), the containing object is included in the
  150. result.
  151. The ``path`` is relative.
  152. """
  153. raise NotImplementedError
  154. @property
  155. def etag(self):
  156. return get_etag(self.serialize())
  157. @classmethod
  158. def create_collection(cls, href, collection=None, tag=None):
  159. """Create a collection.
  160. ``collection`` is a list of vobject components.
  161. ``tag`` is the type of collection (VCALENDAR or VADDRESSBOOK). If
  162. ``tag`` is not given, it is guessed from the collection.
  163. """
  164. raise NotImplementedError
  165. def list(self):
  166. """List collection items."""
  167. raise NotImplementedError
  168. def get(self, href):
  169. """Fetch a single item."""
  170. raise NotImplementedError
  171. def get_multi(self, hrefs):
  172. """Fetch multiple items. Duplicate hrefs must be ignored.
  173. Functionally similar to ``get``, but might bring performance benefits
  174. on some storages when used cleverly.
  175. """
  176. for href in set(hrefs):
  177. yield self.get(href)
  178. def pre_filtered_list(self, filters):
  179. """List collection items with optional pre filtering.
  180. This could largely improve performance of reports depending on
  181. the filters and this implementation.
  182. This returns all event by default
  183. """
  184. return [self.get(href) for href, _ in self.list()]
  185. def has(self, href):
  186. """Check if an item exists by its href.
  187. Functionally similar to ``get``, but might bring performance benefits
  188. on some storages when used cleverly.
  189. """
  190. return self.get(href) is not None
  191. def upload(self, href, vobject_item):
  192. """Upload a new item."""
  193. raise NotImplementedError
  194. def update(self, href, vobject_item, etag=None):
  195. """Update an item.
  196. Functionally similar to ``delete`` plus ``upload``, but might bring
  197. performance benefits on some storages when used cleverly.
  198. """
  199. self.delete(href, etag)
  200. self.upload(href, vobject_item)
  201. def delete(self, href=None, etag=None):
  202. """Delete an item.
  203. When ``href`` is ``None``, delete the collection.
  204. """
  205. raise NotImplementedError
  206. def get_meta(self, key):
  207. """Get metadata value for collection."""
  208. raise NotImplementedError
  209. def set_meta(self, key, value):
  210. """Set metadata value for collection."""
  211. raise NotImplementedError
  212. @property
  213. def last_modified(self):
  214. """Get the HTTP-datetime of when the collection was modified."""
  215. raise NotImplementedError
  216. def serialize(self):
  217. """Get the unicode string representing the whole collection."""
  218. raise NotImplementedError
  219. @classmethod
  220. @contextmanager
  221. def acquire_lock(cls, mode):
  222. """Set a context manager to lock the whole storage.
  223. ``mode`` must either be "r" for shared access or "w" for exclusive
  224. access.
  225. """
  226. raise NotImplementedError
  227. class Collection(BaseCollection):
  228. """Collection stored in several files per calendar."""
  229. def __init__(self, path, principal=False):
  230. folder = os.path.expanduser(
  231. self.configuration.get("storage", "filesystem_folder"))
  232. # path should already be sanitized
  233. self.path = sanitize_path(path).strip("/")
  234. self.storage_encoding = self.configuration.get("encoding", "stock")
  235. self._filesystem_path = path_to_filesystem(folder, self.path)
  236. split_path = self.path.split("/")
  237. if len(split_path) > 1:
  238. # URL with at least one folder
  239. self.owner = split_path[0]
  240. else:
  241. self.owner = None
  242. self.is_principal = principal
  243. @classmethod
  244. def discover(cls, path, depth="1"):
  245. # path == None means wrong URL
  246. if path is None:
  247. return
  248. # path should already be sanitized
  249. sane_path = sanitize_path(path).strip("/")
  250. attributes = sane_path.split("/")
  251. if not attributes:
  252. return
  253. # Try to guess if the path leads to a collection or an item
  254. folder = os.path.expanduser(
  255. cls.configuration.get("storage", "filesystem_folder"))
  256. if not os.path.isdir(path_to_filesystem(folder, sane_path)):
  257. # path is not a collection
  258. if os.path.isfile(path_to_filesystem(folder, sane_path)):
  259. # path is an item
  260. attributes.pop()
  261. elif os.path.isdir(path_to_filesystem(folder, *attributes[:-1])):
  262. # path parent is a collection
  263. attributes.pop()
  264. # TODO: else: return?
  265. path = "/".join(attributes)
  266. principal = len(attributes) <= 1
  267. collection = cls(path, principal)
  268. yield collection
  269. if depth != "0":
  270. # TODO: fix this
  271. items = list(collection.list())
  272. if items:
  273. for item in items:
  274. yield collection.get(item[0])
  275. _, directories, _ = next(os.walk(collection._filesystem_path))
  276. for sub_path in directories:
  277. if not is_safe_filesystem_path_component(sub_path):
  278. cls.logger.debug(
  279. "Skipping collection: %s", sub_path)
  280. continue
  281. full_path = os.path.join(collection._filesystem_path, sub_path)
  282. if os.path.exists(full_path):
  283. yield cls(posixpath.join(path, sub_path))
  284. @classmethod
  285. def create_collection(cls, href, collection=None, tag=None):
  286. folder = os.path.expanduser(
  287. cls.configuration.get("storage", "filesystem_folder"))
  288. path = path_to_filesystem(folder, href)
  289. if not os.path.exists(path):
  290. os.makedirs(path)
  291. if not tag and collection:
  292. tag = collection[0].name
  293. self = cls(href)
  294. if tag == "VCALENDAR":
  295. self.set_meta("tag", "VCALENDAR")
  296. if collection:
  297. collection, = collection
  298. items = []
  299. for content in ("vevent", "vtodo", "vjournal"):
  300. items.extend(getattr(collection, "%s_list" % content, []))
  301. processed_uids = []
  302. for i, item in enumerate(items):
  303. uid = getattr(item, "uid", None)
  304. if uid in processed_uids:
  305. continue
  306. new_collection = vobject.iCalendar()
  307. new_collection.add(item)
  308. if uid:
  309. processed_uids.append(uid)
  310. # search for items with same UID
  311. for oitem in items[i+1:]:
  312. if getattr(oitem, "uid", None) == uid:
  313. new_collection.add(oitem)
  314. self.upload(uuid4().hex, new_collection)
  315. elif tag == "VCARD":
  316. self.set_meta("tag", "VADDRESSBOOK")
  317. if collection:
  318. for card in collection:
  319. self.upload(uuid4().hex, card)
  320. return self
  321. def list(self):
  322. try:
  323. hrefs = os.listdir(self._filesystem_path)
  324. except IOError:
  325. return
  326. for href in hrefs:
  327. if not is_safe_filesystem_path_component(href):
  328. self.logger.debug(
  329. "Skipping component: %s", href)
  330. continue
  331. path = os.path.join(self._filesystem_path, href)
  332. if not href.endswith(".props") and os.path.isfile(path):
  333. with open(path, encoding=self.storage_encoding) as fd:
  334. yield href, get_etag(fd.read())
  335. def get(self, href):
  336. if not href:
  337. return
  338. href = href.strip("{}").replace("/", "_")
  339. if is_safe_filesystem_path_component(href):
  340. path = os.path.join(self._filesystem_path, href)
  341. if os.path.isfile(path):
  342. with open(path, encoding=self.storage_encoding) as fd:
  343. text = fd.read()
  344. last_modified = time.strftime(
  345. "%a, %d %b %Y %H:%M:%S GMT",
  346. time.gmtime(os.path.getmtime(path)))
  347. return Item(self, vobject.readOne(text), href, last_modified)
  348. else:
  349. self.logger.debug(
  350. "Can't tranlate name safely to filesystem, "
  351. "skipping component: %s", href)
  352. def has(self, href):
  353. return self.get(href) is not None
  354. def upload(self, href, vobject_item):
  355. # TODO: use returned object in code
  356. if is_safe_filesystem_path_component(href):
  357. path = path_to_filesystem(self._filesystem_path, href)
  358. if not os.path.exists(path):
  359. item = Item(self, vobject_item, href)
  360. with open(path, "w", encoding=self.storage_encoding) as fd:
  361. fd.write(item.serialize())
  362. return item
  363. else:
  364. self.logger.debug(
  365. "Can't tranlate name safely to filesystem, "
  366. "skipping component: %s", href)
  367. def update(self, href, vobject_item, etag=None):
  368. # TODO: use etag in code and test it here
  369. # TODO: use returned object in code
  370. if is_safe_filesystem_path_component(href):
  371. path = path_to_filesystem(self._filesystem_path, href)
  372. if os.path.exists(path):
  373. with open(path, encoding=self.storage_encoding) as fd:
  374. text = fd.read()
  375. if not etag or etag == get_etag(text):
  376. item = Item(self, vobject_item, href)
  377. with open(path, "w", encoding=self.storage_encoding) as fd:
  378. fd.write(item.serialize())
  379. return item
  380. else:
  381. self.logger.debug(
  382. "Can't tranlate name safely to filesystem, "
  383. "skipping component: %s", href)
  384. def delete(self, href=None, etag=None):
  385. # TODO: use etag in code and test it here
  386. # TODO: use returned object in code
  387. if href is None:
  388. # Delete the collection
  389. if os.path.isdir(self._filesystem_path):
  390. shutil.rmtree(self._filesystem_path)
  391. props_path = self._filesystem_path + ".props"
  392. if os.path.isfile(props_path):
  393. os.remove(props_path)
  394. return
  395. elif is_safe_filesystem_path_component(href):
  396. # Delete an item
  397. path = path_to_filesystem(self._filesystem_path, href)
  398. if os.path.isfile(path):
  399. with open(path, encoding=self.storage_encoding) as fd:
  400. text = fd.read()
  401. if not etag or etag == get_etag(text):
  402. os.remove(path)
  403. return
  404. else:
  405. self.logger.debug(
  406. "Can't tranlate name safely to filesystem, "
  407. "skipping component: %s", href)
  408. def get_meta(self, key):
  409. props_path = self._filesystem_path + ".props"
  410. if os.path.exists(props_path):
  411. with open(props_path, encoding=self.storage_encoding) as prop:
  412. return json.load(prop).get(key)
  413. def set_meta(self, key, value):
  414. props_path = self._filesystem_path + ".props"
  415. properties = {}
  416. if os.path.exists(props_path):
  417. with open(props_path, encoding=self.storage_encoding) as prop:
  418. properties.update(json.load(prop))
  419. if value:
  420. properties[key] = value
  421. else:
  422. properties.pop(key, None)
  423. with open(props_path, "w+", encoding=self.storage_encoding) as prop:
  424. json.dump(properties, prop)
  425. @property
  426. def last_modified(self):
  427. last = max([os.path.getmtime(self._filesystem_path)] + [
  428. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  429. for filename in os.listdir(self._filesystem_path)] or [0])
  430. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  431. def serialize(self):
  432. items = []
  433. for href in os.listdir(self._filesystem_path):
  434. path = os.path.join(self._filesystem_path, href)
  435. if os.path.isfile(path) and not path.endswith(".props"):
  436. with open(path, encoding=self.storage_encoding) as fd:
  437. items.append(vobject.readOne(fd.read()))
  438. if self.get_meta("tag") == "VCALENDAR":
  439. collection = vobject.iCalendar()
  440. for item in items:
  441. for content in ("vevent", "vtodo", "vjournal"):
  442. if content in item.contents:
  443. for item_part in getattr(item, "%s_list" % content):
  444. collection.add(item_part)
  445. break
  446. return collection.serialize()
  447. elif self.get_meta("tag") == "VADDRESSBOOK":
  448. return "".join([item.serialize() for item in items])
  449. return ""
  450. _lock = threading.Lock()
  451. _waiters = []
  452. _lock_file = None
  453. _lock_file_locked = False
  454. _readers = 0
  455. _writer = False
  456. @classmethod
  457. @contextmanager
  458. def acquire_lock(cls, mode):
  459. def condition():
  460. if mode == "r":
  461. return not cls._writer
  462. else:
  463. return not cls._writer and cls._readers == 0
  464. if mode not in ("r", "w"):
  465. raise ValueError("Invalid lock mode: %s" % mode)
  466. # Use a primitive lock which only works within one process as a
  467. # precondition for inter-process file-based locking
  468. with cls._lock:
  469. if cls._waiters or not condition():
  470. # use FIFO for access requests
  471. waiter = threading.Condition(lock=cls._lock)
  472. cls._waiters.append(waiter)
  473. while True:
  474. waiter.wait()
  475. if condition():
  476. break
  477. cls._waiters.pop(0)
  478. if mode == "r":
  479. cls._readers += 1
  480. # notify additional potential readers
  481. if cls._waiters:
  482. cls._waiters[0].notify()
  483. else:
  484. cls._writer = True
  485. if not cls._lock_file:
  486. folder = os.path.expanduser(
  487. cls.configuration.get("storage", "filesystem_folder"))
  488. if not os.path.exists(folder):
  489. os.makedirs(folder, exist_ok=True)
  490. lock_path = os.path.join(folder, ".Radicale.lock")
  491. cls._lock_file = open(lock_path, "w+")
  492. # set access rights to a necessary minimum to prevent locking
  493. # by arbitrary users
  494. try:
  495. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  496. except OSError:
  497. cls.logger.debug("Failed to set permissions on lock file")
  498. if not cls._lock_file_locked:
  499. if os.name == "nt":
  500. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  501. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  502. overlapped = Overlapped()
  503. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  504. cls.logger.debug("Locking not supported")
  505. elif os.name == "posix":
  506. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  507. try:
  508. fcntl.lockf(cls._lock_file.fileno(), _cmd)
  509. except OSError:
  510. cls.logger.debug("Locking not supported")
  511. cls._lock_file_locked = True
  512. try:
  513. yield
  514. finally:
  515. with cls._lock:
  516. if mode == "r":
  517. cls._readers -= 1
  518. else:
  519. cls._writer = False
  520. if cls._readers == 0:
  521. if os.name == "nt":
  522. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  523. overlapped = Overlapped()
  524. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  525. cls.logger.debug("Unlocking not supported")
  526. elif os.name == "posix":
  527. try:
  528. fcntl.lockf(cls._lock_file.fileno(),
  529. fcntl.LOCK_UN)
  530. except OSError:
  531. cls.logger.debug("Unlocking not supported")
  532. cls._lock_file_locked = False
  533. if cls._waiters:
  534. cls._waiters[0].notify()