storage.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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. Conversion is done in a secure manner, or raises ``ValueError``.
  108. """
  109. root = sanitize_path(root)
  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. @contextmanager
  199. def at_once(self):
  200. """Set a context manager buffering the reads and writes."""
  201. # TODO: use in code
  202. yield
  203. def get_meta(self, key):
  204. """Get metadata value for collection."""
  205. raise NotImplementedError
  206. def set_meta(self, key, value):
  207. """Set metadata value for collection."""
  208. raise NotImplementedError
  209. @property
  210. def last_modified(self):
  211. """Get the HTTP-datetime of when the collection was modified."""
  212. raise NotImplementedError
  213. def serialize(self):
  214. """Get the unicode string representing the whole collection."""
  215. raise NotImplementedError
  216. @classmethod
  217. @contextmanager
  218. def acquire_lock(cls, mode):
  219. """Set a context manager to lock the whole storage.
  220. ``mode`` must either be "r" for shared access or "w" for exclusive
  221. access.
  222. """
  223. raise NotImplementedError
  224. class Collection(BaseCollection):
  225. """Collection stored in several files per calendar."""
  226. def __init__(self, path, principal=False):
  227. folder = os.path.expanduser(
  228. self.configuration.get("storage", "filesystem_folder"))
  229. # path should already be sanitized
  230. self.path = sanitize_path(path).strip("/")
  231. self.storage_encoding = self.configuration.get("encoding", "stock")
  232. self._filesystem_path = path_to_filesystem(folder, self.path)
  233. split_path = self.path.split("/")
  234. if len(split_path) > 1:
  235. # URL with at least one folder
  236. self.owner = split_path[0]
  237. else:
  238. self.owner = None
  239. self.is_principal = principal
  240. @classmethod
  241. def discover(cls, path, depth="1"):
  242. # path == None means wrong URL
  243. if path is None:
  244. return
  245. # path should already be sanitized
  246. sane_path = sanitize_path(path).strip("/")
  247. attributes = sane_path.split("/")
  248. if not attributes:
  249. return
  250. # Try to guess if the path leads to a collection or an item
  251. folder = os.path.expanduser(
  252. cls.configuration.get("storage", "filesystem_folder"))
  253. if not os.path.isdir(path_to_filesystem(folder, sane_path)):
  254. # path is not a collection
  255. if os.path.isfile(path_to_filesystem(folder, sane_path)):
  256. # path is an item
  257. attributes.pop()
  258. elif os.path.isdir(path_to_filesystem(folder, *attributes[:-1])):
  259. # path parent is a collection
  260. attributes.pop()
  261. # TODO: else: return?
  262. path = "/".join(attributes)
  263. principal = len(attributes) <= 1
  264. collection = cls(path, principal)
  265. yield collection
  266. if depth != "0":
  267. # TODO: fix this
  268. items = list(collection.list())
  269. if items:
  270. for item in items:
  271. yield collection.get(item[0])
  272. _, directories, _ = next(os.walk(collection._filesystem_path))
  273. for sub_path in directories:
  274. full_path = os.path.join(collection._filesystem_path, sub_path)
  275. if os.path.exists(path_to_filesystem(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. for content in ("vevent", "vtodo", "vjournal"):
  292. if content in collection.contents:
  293. for item in getattr(collection, "%s_list" % content):
  294. new_collection = vobject.iCalendar()
  295. new_collection.add(item)
  296. self.upload(uuid4().hex, new_collection)
  297. elif tag == "VCARD":
  298. self.set_meta("tag", "VADDRESSBOOK")
  299. if collection:
  300. for card in collection:
  301. self.upload(uuid4().hex, card)
  302. return self
  303. def list(self):
  304. try:
  305. hrefs = os.listdir(self._filesystem_path)
  306. except IOError:
  307. return
  308. for href in hrefs:
  309. path = os.path.join(self._filesystem_path, href)
  310. if not href.endswith(".props") and os.path.isfile(path):
  311. with open(path, encoding=self.storage_encoding) as fd:
  312. yield href, get_etag(fd.read())
  313. def get(self, href):
  314. if not href:
  315. return
  316. href = href.strip("{}").replace("/", "_")
  317. if is_safe_filesystem_path_component(href):
  318. path = os.path.join(self._filesystem_path, href)
  319. if os.path.isfile(path):
  320. with open(path, encoding=self.storage_encoding) as fd:
  321. text = fd.read()
  322. last_modified = time.strftime(
  323. "%a, %d %b %Y %H:%M:%S GMT",
  324. time.gmtime(os.path.getmtime(path)))
  325. return Item(self, vobject.readOne(text), href, last_modified)
  326. else:
  327. self.logger.debug(
  328. "Can't tranlate name safely to filesystem, "
  329. "skipping component: %s", href)
  330. def has(self, href):
  331. return self.get(href) is not None
  332. def upload(self, href, vobject_item):
  333. # TODO: use returned object in code
  334. if is_safe_filesystem_path_component(href):
  335. path = path_to_filesystem(self._filesystem_path, href)
  336. if not os.path.exists(path):
  337. item = Item(self, vobject_item, href)
  338. with open(path, "w", encoding=self.storage_encoding) as fd:
  339. fd.write(item.serialize())
  340. return item
  341. else:
  342. self.logger.debug(
  343. "Can't tranlate name safely to filesystem, "
  344. "skipping component: %s", href)
  345. def update(self, href, vobject_item, etag=None):
  346. # TODO: use etag in code and test it here
  347. # TODO: use returned object in code
  348. if is_safe_filesystem_path_component(href):
  349. path = path_to_filesystem(self._filesystem_path, href)
  350. if os.path.exists(path):
  351. with open(path, encoding=self.storage_encoding) as fd:
  352. text = fd.read()
  353. if not etag or etag == get_etag(text):
  354. item = Item(self, vobject_item, href)
  355. with open(path, "w", encoding=self.storage_encoding) as fd:
  356. fd.write(item.serialize())
  357. return item
  358. else:
  359. self.logger.debug(
  360. "Can't tranlate name safely to filesystem, "
  361. "skipping component: %s", href)
  362. def delete(self, href=None, etag=None):
  363. # TODO: use etag in code and test it here
  364. # TODO: use returned object in code
  365. if href is None:
  366. # Delete the collection
  367. if os.path.isdir(self._filesystem_path):
  368. shutil.rmtree(self._filesystem_path)
  369. props_path = self._filesystem_path + ".props"
  370. if os.path.isfile(props_path):
  371. os.remove(props_path)
  372. return
  373. elif is_safe_filesystem_path_component(href):
  374. # Delete an item
  375. path = path_to_filesystem(self._filesystem_path, href)
  376. if os.path.isfile(path):
  377. with open(path, encoding=self.storage_encoding) as fd:
  378. text = fd.read()
  379. if not etag or etag == get_etag(text):
  380. os.remove(path)
  381. return
  382. else:
  383. self.logger.debug(
  384. "Can't tranlate name safely to filesystem, "
  385. "skipping component: %s", href)
  386. @contextmanager
  387. def at_once(self):
  388. # TODO: use a file locker
  389. yield
  390. def get_meta(self, key):
  391. props_path = self._filesystem_path + ".props"
  392. if os.path.exists(props_path):
  393. with open(props_path, encoding=self.storage_encoding) as prop:
  394. return json.load(prop).get(key)
  395. def set_meta(self, key, value):
  396. props_path = self._filesystem_path + ".props"
  397. properties = {}
  398. if os.path.exists(props_path):
  399. with open(props_path, encoding=self.storage_encoding) as prop:
  400. properties.update(json.load(prop))
  401. if value:
  402. properties[key] = value
  403. else:
  404. properties.pop(key, None)
  405. with open(props_path, "w+", encoding=self.storage_encoding) as prop:
  406. json.dump(properties, prop)
  407. @property
  408. def last_modified(self):
  409. last = max([os.path.getmtime(self._filesystem_path)] + [
  410. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  411. for filename in os.listdir(self._filesystem_path)] or [0])
  412. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  413. def serialize(self):
  414. items = []
  415. for href in os.listdir(self._filesystem_path):
  416. path = os.path.join(self._filesystem_path, href)
  417. if os.path.isfile(path) and not path.endswith(".props"):
  418. with open(path, encoding=self.storage_encoding) as fd:
  419. items.append(vobject.readOne(fd.read()))
  420. if self.get_meta("tag") == "VCALENDAR":
  421. collection = vobject.iCalendar()
  422. for item in items:
  423. for content in ("vevent", "vtodo", "vjournal"):
  424. if content in item.contents:
  425. collection.add(getattr(item, content))
  426. break
  427. return collection.serialize()
  428. elif self.get_meta("tag") == "VADDRESSBOOK":
  429. return "".join([item.serialize() for item in items])
  430. return ""
  431. _lock = threading.Lock()
  432. _waiters = []
  433. _lock_file = None
  434. _lock_file_locked = False
  435. _readers = 0
  436. _writer = False
  437. @classmethod
  438. @contextmanager
  439. def acquire_lock(cls, mode):
  440. def condition():
  441. if mode == "r":
  442. return not cls._writer
  443. else:
  444. return not cls._writer and cls._readers == 0
  445. if mode not in ("r", "w"):
  446. raise ValueError("Invalid lock mode: %s" % mode)
  447. # Use a primitive lock which only works within one process as a
  448. # precondition for inter-process file-based locking
  449. with cls._lock:
  450. if cls._waiters or not condition():
  451. # use FIFO for access requests
  452. waiter = threading.Condition(lock=cls._lock)
  453. cls._waiters.append(waiter)
  454. while True:
  455. waiter.wait()
  456. if condition():
  457. break
  458. cls._waiters.pop(0)
  459. if mode == "r":
  460. cls._readers += 1
  461. # notify additional potential readers
  462. if cls._waiters:
  463. cls._waiters[0].notify()
  464. else:
  465. cls._writer = True
  466. if not cls._lock_file:
  467. folder = os.path.expanduser(
  468. cls.configuration.get("storage", "filesystem_folder"))
  469. if not os.path.exists(folder):
  470. os.makedirs(folder, exist_ok=True)
  471. lock_path = os.path.join(folder, "Radicale.lock")
  472. cls._lock_file = open(lock_path, "w+")
  473. # set access rights to a necessary minimum to prevent locking
  474. # by arbitrary users
  475. try:
  476. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  477. except OSError:
  478. cls.logger.debug("Failed to set permissions on lock file")
  479. if not cls._lock_file_locked:
  480. if os.name == "nt":
  481. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  482. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  483. overlapped = Overlapped()
  484. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  485. cls.logger.debug("Locking not supported")
  486. elif os.name == "posix":
  487. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  488. try:
  489. fcntl.lockf(cls._lock_file.fileno(), _cmd)
  490. except OSError:
  491. cls.logger.debug("Locking not supported")
  492. cls._lock_file_locked = True
  493. yield
  494. with cls._lock:
  495. if mode == "r":
  496. cls._readers -= 1
  497. else:
  498. cls._writer = False
  499. if cls._readers == 0:
  500. if os.name == "nt":
  501. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  502. overlapped = Overlapped()
  503. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  504. cls.logger.debug("Unlocking not supported")
  505. elif os.name == "posix":
  506. try:
  507. fcntl.lockf(cls._lock_file.fileno(), fcntl.LOCK_UN)
  508. except OSError:
  509. cls.logger.debug("Unlocking not supported")
  510. cls._lock_file_locked = False
  511. if cls._waiters:
  512. cls._waiters[0].notify()