storage.py 23 KB

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