storage.py 21 KB

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