storage.py 22 KB

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