storage.py 22 KB

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