storage.py 23 KB

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