storage.py 23 KB

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