storage.py 23 KB

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