storage.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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 shlex
  28. import stat
  29. import subprocess
  30. import threading
  31. import time
  32. from contextlib import contextmanager
  33. from hashlib import md5
  34. from importlib import import_module
  35. from itertools import groupby
  36. from random import getrandbits
  37. from tempfile import TemporaryDirectory, NamedTemporaryFile
  38. import vobject
  39. if os.name == "nt":
  40. import ctypes
  41. import ctypes.wintypes
  42. import msvcrt
  43. LOCKFILE_EXCLUSIVE_LOCK = 2
  44. if ctypes.sizeof(ctypes.c_void_p) == 4:
  45. ULONG_PTR = ctypes.c_uint32
  46. else:
  47. ULONG_PTR = ctypes.c_uint64
  48. class Overlapped(ctypes.Structure):
  49. _fields_ = [
  50. ("internal", ULONG_PTR),
  51. ("internal_high", ULONG_PTR),
  52. ("offset", ctypes.wintypes.DWORD),
  53. ("offset_high", ctypes.wintypes.DWORD),
  54. ("h_event", ctypes.wintypes.HANDLE)]
  55. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  56. lock_file_ex.argtypes = [
  57. ctypes.wintypes.HANDLE,
  58. ctypes.wintypes.DWORD,
  59. ctypes.wintypes.DWORD,
  60. ctypes.wintypes.DWORD,
  61. ctypes.wintypes.DWORD,
  62. ctypes.POINTER(Overlapped)]
  63. lock_file_ex.restype = ctypes.wintypes.BOOL
  64. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  65. unlock_file_ex.argtypes = [
  66. ctypes.wintypes.HANDLE,
  67. ctypes.wintypes.DWORD,
  68. ctypes.wintypes.DWORD,
  69. ctypes.wintypes.DWORD,
  70. ctypes.POINTER(Overlapped)]
  71. unlock_file_ex.restype = ctypes.wintypes.BOOL
  72. elif os.name == "posix":
  73. import fcntl
  74. def load(configuration, logger):
  75. """Load the storage manager chosen in configuration."""
  76. storage_type = configuration.get("storage", "type")
  77. if storage_type == "multifilesystem":
  78. collection_class = Collection
  79. else:
  80. collection_class = import_module(storage_type).Collection
  81. class CollectionCopy(collection_class):
  82. """Collection copy, avoids overriding the original class attributes."""
  83. CollectionCopy.configuration = configuration
  84. CollectionCopy.logger = logger
  85. return CollectionCopy
  86. def get_etag(text):
  87. """Etag from collection or item."""
  88. etag = md5()
  89. etag.update(text.encode("utf-8"))
  90. return '"%s"' % etag.hexdigest()
  91. def get_uid(item):
  92. """UID value of an item if defined."""
  93. return hasattr(item, "uid") and item.uid.value
  94. def sanitize_path(path):
  95. """Make path absolute with leading slash to prevent access to other data.
  96. Preserve a potential trailing slash.
  97. """
  98. trailing_slash = "/" if path.endswith("/") else ""
  99. path = posixpath.normpath(path)
  100. new_path = "/"
  101. for part in path.split("/"):
  102. if not part or part in (".", ".."):
  103. continue
  104. new_path = posixpath.join(new_path, part)
  105. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  106. return new_path + trailing_slash
  107. def is_safe_path_component(path):
  108. """Check if path is a single component of a path.
  109. Check that the path is safe to join too.
  110. """
  111. return path and "/" not in path and path not in (".", "..")
  112. def is_safe_filesystem_path_component(path):
  113. """Check if path is a single component of a filesystem path.
  114. Check that the path is safe to join too.
  115. """
  116. return (
  117. path and not os.path.splitdrive(path)[0] and
  118. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  119. not path.startswith(".") and not path.endswith("~"))
  120. def path_to_filesystem(root, *paths):
  121. """Convert path to a local filesystem path relative to base_folder.
  122. `root` must be a secure filesystem path, it will be prepend to the path.
  123. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  124. """
  125. paths = [sanitize_path(path).strip("/") for path in paths]
  126. safe_path = root
  127. for path in paths:
  128. if not path:
  129. continue
  130. for part in path.split("/"):
  131. if not is_safe_filesystem_path_component(part):
  132. raise UnsafePathError(part)
  133. safe_path = os.path.join(safe_path, part)
  134. return safe_path
  135. class UnsafePathError(ValueError):
  136. def __init__(self, path):
  137. message = "Can't translate name safely to filesystem: %s" % path
  138. super().__init__(message)
  139. class ComponentExistsError(ValueError):
  140. def __init__(self, path):
  141. message = "Component already exists: %s" % path
  142. super().__init__(message)
  143. class ComponentNotFoundError(ValueError):
  144. def __init__(self, path):
  145. message = "Component doesn't exist: %s" % path
  146. super().__init__(message)
  147. class EtagMismatchError(ValueError):
  148. def __init__(self, etag1, etag2):
  149. message = "ETags don't match: %s != %s" % (etag1, etag2)
  150. super().__init__(message)
  151. class Item:
  152. def __init__(self, collection, item, href, last_modified=None):
  153. self.collection = collection
  154. self.item = item
  155. self.href = href
  156. self.last_modified = last_modified
  157. def __getattr__(self, attr):
  158. return getattr(self.item, attr)
  159. @property
  160. def etag(self):
  161. return get_etag(self.serialize())
  162. class BaseCollection:
  163. # Overriden on copy by the "load" function
  164. configuration = None
  165. logger = None
  166. def __init__(self, path, principal=False):
  167. """Initialize the collection.
  168. ``path`` must be the normalized relative path of the collection, using
  169. the slash as the folder delimiter, with no leading nor trailing slash.
  170. """
  171. raise NotImplementedError
  172. @classmethod
  173. def discover(cls, path, depth="0"):
  174. """Discover a list of collections under the given ``path``.
  175. If ``depth`` is "0", only the actual object under ``path`` is
  176. returned.
  177. If ``depth`` is anything but "0", it is considered as "1" and direct
  178. children are included in the result.
  179. The ``path`` is relative.
  180. The root collection "/" must always exist.
  181. """
  182. raise NotImplementedError
  183. @classmethod
  184. def move(cls, item, to_collection, to_href):
  185. """Move an object.
  186. ``item`` is the item to move.
  187. ``to_collection`` is the target collection.
  188. ``to_href`` is the target name in ``to_collection``. An item with the
  189. same name might already exist.
  190. """
  191. if item.collection.path == to_collection.path and item.href == to_href:
  192. return
  193. to_collection.upload(to_href, item.item)
  194. item.collection.delete(item.href)
  195. @property
  196. def etag(self):
  197. return get_etag(self.serialize())
  198. @classmethod
  199. def create_collection(cls, href, collection=None, props=None):
  200. """Create a collection.
  201. If the collection already exists and neither ``collection`` nor
  202. ``props`` are set, this method shouldn't do anything. Otherwise the
  203. existing collection must be replaced.
  204. ``collection`` is a list of vobject components.
  205. ``props`` are metadata values for the collection.
  206. ``props["tag"]`` is the type of collection (VCALENDAR or
  207. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  208. collection.
  209. """
  210. raise NotImplementedError
  211. def list(self):
  212. """List collection items."""
  213. raise NotImplementedError
  214. def get(self, href):
  215. """Fetch a single item."""
  216. raise NotImplementedError
  217. def get_multi(self, hrefs):
  218. """Fetch multiple items. Duplicate hrefs must be ignored.
  219. Functionally similar to ``get``, but might bring performance benefits
  220. on some storages when used cleverly.
  221. """
  222. for href in set(hrefs):
  223. yield self.get(href)
  224. def pre_filtered_list(self, filters):
  225. """List collection items with optional pre filtering.
  226. This could largely improve performance of reports depending on
  227. the filters and this implementation.
  228. This returns all event by default
  229. """
  230. return [self.get(href) for href in self.list()]
  231. def has(self, href):
  232. """Check if an item exists by its href.
  233. Functionally similar to ``get``, but might bring performance benefits
  234. on some storages when used cleverly.
  235. """
  236. return self.get(href) is not None
  237. def upload(self, href, vobject_item):
  238. """Upload a new or replace an existing item."""
  239. raise NotImplementedError
  240. def delete(self, href=None):
  241. """Delete an item.
  242. When ``href`` is ``None``, delete the collection.
  243. """
  244. raise NotImplementedError
  245. def get_meta(self, key):
  246. """Get metadata value for collection."""
  247. raise NotImplementedError
  248. def set_meta(self, props):
  249. """Set metadata values for collection."""
  250. raise NotImplementedError
  251. @property
  252. def last_modified(self):
  253. """Get the HTTP-datetime of when the collection was modified."""
  254. raise NotImplementedError
  255. def serialize(self):
  256. """Get the unicode string representing the whole collection."""
  257. raise NotImplementedError
  258. @classmethod
  259. @contextmanager
  260. def acquire_lock(cls, mode, user=None):
  261. """Set a context manager to lock the whole storage.
  262. ``mode`` must either be "r" for shared access or "w" for exclusive
  263. access.
  264. ``user`` is the name of the logged in user or empty.
  265. """
  266. raise NotImplementedError
  267. class Collection(BaseCollection):
  268. """Collection stored in several files per calendar."""
  269. def __init__(self, path, principal=False, folder=None):
  270. if not folder:
  271. folder = self._get_collection_root_folder()
  272. # Path should already be sanitized
  273. self.path = sanitize_path(path).strip("/")
  274. self.encoding = self.configuration.get("encoding", "stock")
  275. self._filesystem_path = path_to_filesystem(folder, self.path)
  276. self._props_path = os.path.join(
  277. self._filesystem_path, ".Radicale.props")
  278. split_path = self.path.split("/")
  279. self.owner = split_path[0] if len(split_path) > 1 else None
  280. self.is_principal = principal
  281. @classmethod
  282. def _get_collection_root_folder(cls):
  283. filesystem_folder = os.path.expanduser(
  284. cls.configuration.get("storage", "filesystem_folder"))
  285. return os.path.join(filesystem_folder, "collection-root")
  286. @contextmanager
  287. def _atomic_write(self, path, mode="w", newline=None):
  288. directory = os.path.dirname(path)
  289. tmp = NamedTemporaryFile(
  290. mode=mode, dir=directory, encoding=self.encoding,
  291. delete=False, prefix=".Radicale.tmp-", newline=newline)
  292. try:
  293. yield tmp
  294. if self.configuration.getboolean("storage", "filesystem_fsync"):
  295. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  296. fcntl.fcntl(tmp.fileno(), fcntl.F_FULLFSYNC)
  297. else:
  298. os.fsync(tmp.fileno())
  299. tmp.close()
  300. os.replace(tmp.name, path)
  301. except:
  302. tmp.close()
  303. os.remove(tmp.name)
  304. raise
  305. self._sync_directory(directory)
  306. @staticmethod
  307. def _find_available_file_name(exists_fn):
  308. # Prevent infinite loop
  309. for _ in range(10000):
  310. file_name = hex(getrandbits(32))[2:]
  311. if not exists_fn(file_name):
  312. return file_name
  313. raise FileExistsError(errno.EEXIST, "No usable file name found")
  314. @classmethod
  315. def _sync_directory(cls, path):
  316. """Sync directory to disk.
  317. This only works on POSIX and does nothing on other systems.
  318. """
  319. if not cls.configuration.getboolean("storage", "filesystem_fsync"):
  320. return
  321. if os.name == "posix":
  322. fd = os.open(path, 0)
  323. try:
  324. if hasattr(fcntl, "F_FULLFSYNC"):
  325. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  326. else:
  327. os.fsync(fd)
  328. finally:
  329. os.close(fd)
  330. @classmethod
  331. def _makedirs_synced(cls, filesystem_path):
  332. """Recursively create a directory and its parents in a sync'ed way.
  333. This method acts silently when the folder already exists.
  334. """
  335. if os.path.isdir(filesystem_path):
  336. return
  337. parent_filesystem_path = os.path.dirname(filesystem_path)
  338. # Prevent infinite loop
  339. if filesystem_path != parent_filesystem_path:
  340. # Create parent dirs recursively
  341. cls._makedirs_synced(parent_filesystem_path)
  342. # Possible race!
  343. os.makedirs(filesystem_path, exist_ok=True)
  344. cls._sync_directory(parent_filesystem_path)
  345. @classmethod
  346. def discover(cls, path, depth="0"):
  347. if path is None:
  348. # Wrong URL
  349. return
  350. # Path should already be sanitized
  351. sane_path = sanitize_path(path).strip("/")
  352. attributes = sane_path.split("/")
  353. if not attributes[0]:
  354. attributes.pop()
  355. folder = cls._get_collection_root_folder()
  356. # Create the root collection
  357. cls._makedirs_synced(folder)
  358. try:
  359. filesystem_path = path_to_filesystem(folder, sane_path)
  360. except ValueError:
  361. # Path is unsafe
  362. return
  363. # Check if the path exists and if it leads to a collection or an item
  364. if not os.path.isdir(filesystem_path):
  365. if attributes and os.path.isfile(filesystem_path):
  366. href = attributes.pop()
  367. else:
  368. return
  369. else:
  370. href = None
  371. path = "/".join(attributes)
  372. principal = len(attributes) == 1
  373. collection = cls(path, principal)
  374. if href:
  375. yield collection.get(href)
  376. return
  377. yield collection
  378. if depth == "0":
  379. return
  380. for item in collection.list():
  381. yield collection.get(item)
  382. for href in os.listdir(filesystem_path):
  383. if not is_safe_filesystem_path_component(href):
  384. if not href.startswith(".Radicale"):
  385. cls.logger.debug("Skipping collection: %s", href)
  386. continue
  387. child_filesystem_path = path_to_filesystem(filesystem_path, href)
  388. if os.path.isdir(child_filesystem_path):
  389. child_path = posixpath.join(path, href)
  390. child_principal = len(attributes) == 0
  391. yield cls(child_path, child_principal)
  392. @classmethod
  393. def create_collection(cls, href, collection=None, props=None):
  394. folder = cls._get_collection_root_folder()
  395. # Path should already be sanitized
  396. sane_path = sanitize_path(href).strip("/")
  397. attributes = sane_path.split("/")
  398. if not attributes[0]:
  399. attributes.pop()
  400. principal = len(attributes) == 1
  401. filesystem_path = path_to_filesystem(folder, sane_path)
  402. if not props:
  403. props = {}
  404. if not props.get("tag") and collection:
  405. props["tag"] = collection[0].name
  406. if not props:
  407. cls._makedirs_synced(filesystem_path)
  408. return cls(sane_path, principal=principal)
  409. parent_dir = os.path.dirname(filesystem_path)
  410. cls._makedirs_synced(parent_dir)
  411. # Create a temporary directory with an unsafe name
  412. with TemporaryDirectory(
  413. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  414. # The temporary directory itself can't be renamed
  415. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  416. os.makedirs(tmp_filesystem_path)
  417. self = cls("/", principal=principal, folder=tmp_filesystem_path)
  418. self.set_meta(props)
  419. if collection:
  420. if props.get("tag") == "VCALENDAR":
  421. collection, = collection
  422. items = []
  423. for content in ("vevent", "vtodo", "vjournal"):
  424. items.extend(
  425. getattr(collection, "%s_list" % content, []))
  426. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  427. vobject_items = {}
  428. for uid, items in items_by_uid:
  429. new_collection = vobject.iCalendar()
  430. for item in items:
  431. new_collection.add(item)
  432. href = self._find_available_file_name(
  433. vobject_items.get)
  434. vobject_items[href] = new_collection
  435. self.upload_all_nonatomic(vobject_items)
  436. elif props.get("tag") == "VCARD":
  437. vobject_items = {}
  438. for card in collection:
  439. href = self._find_available_file_name(
  440. vobject_items.get)
  441. vobject_items[href] = card
  442. self.upload_all_nonatomic(vobject_items)
  443. # This operation is not atomic on the filesystem level but it's
  444. # very unlikely that one rename operations succeeds while the
  445. # other fails or that only one gets written to disk.
  446. if os.path.exists(filesystem_path):
  447. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  448. os.rename(tmp_filesystem_path, filesystem_path)
  449. cls._sync_directory(parent_dir)
  450. return cls(sane_path, principal=principal)
  451. def upload_all_nonatomic(self, vobject_items):
  452. """Upload a new set of items.
  453. This takes a mapping of href and vobject items and
  454. uploads them nonatomic and without existence checks.
  455. """
  456. fs = []
  457. for href, item in vobject_items.items():
  458. path = path_to_filesystem(self._filesystem_path, href)
  459. fs.append(open(path, "w", encoding=self.encoding, newline=""))
  460. fs[-1].write(item.serialize())
  461. fsync_fn = lambda fd: None
  462. if self.configuration.getboolean("storage", "filesystem_fsync"):
  463. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  464. fsync_fn = lambda fd: fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  465. else:
  466. fsync_fn = os.fsync
  467. # sync everything at once because it's slightly faster.
  468. for f in fs:
  469. fsync_fn(f.fileno())
  470. f.close()
  471. self._sync_directory(self._filesystem_path)
  472. @classmethod
  473. def move(cls, item, to_collection, to_href):
  474. os.replace(
  475. path_to_filesystem(item.collection._filesystem_path, item.href),
  476. path_to_filesystem(to_collection._filesystem_path, to_href))
  477. cls._sync_directory(to_collection._filesystem_path)
  478. if item.collection._filesystem_path != to_collection._filesystem_path:
  479. cls._sync_directory(item.collection._filesystem_path)
  480. def list(self):
  481. try:
  482. hrefs = os.listdir(self._filesystem_path)
  483. except IOError:
  484. return
  485. for href in hrefs:
  486. if not is_safe_filesystem_path_component(href):
  487. if not href.startswith(".Radicale"):
  488. self.logger.debug("Skipping component: %s", href)
  489. continue
  490. path = os.path.join(self._filesystem_path, href)
  491. if os.path.isfile(path):
  492. yield href
  493. def get(self, href):
  494. if not href:
  495. return None
  496. href = href.strip("{}").replace("/", "_")
  497. if not is_safe_filesystem_path_component(href):
  498. self.logger.debug(
  499. "Can't translate name safely to filesystem: %s", href)
  500. return None
  501. path = path_to_filesystem(self._filesystem_path, href)
  502. if not os.path.isfile(path):
  503. return None
  504. with open(path, encoding=self.encoding, newline="") as fd:
  505. text = fd.read()
  506. last_modified = time.strftime(
  507. "%a, %d %b %Y %H:%M:%S GMT",
  508. time.gmtime(os.path.getmtime(path)))
  509. return Item(self, vobject.readOne(text), href, last_modified)
  510. def has(self, href):
  511. return self.get(href) is not None
  512. def upload(self, href, vobject_item):
  513. if not is_safe_filesystem_path_component(href):
  514. raise UnsafePathError(href)
  515. path = path_to_filesystem(self._filesystem_path, href)
  516. item = Item(self, vobject_item, href)
  517. with self._atomic_write(path, newline="") as fd:
  518. fd.write(item.serialize())
  519. return item
  520. def delete(self, href=None):
  521. if href is None:
  522. # Delete the collection
  523. if os.path.isdir(self._filesystem_path):
  524. parent_dir = os.path.dirname(self._filesystem_path)
  525. try:
  526. os.rmdir(self._filesystem_path)
  527. except OSError:
  528. with TemporaryDirectory(
  529. prefix=".Radicale.tmp-", dir=parent_dir) as tmp:
  530. os.rename(self._filesystem_path, os.path.join(
  531. tmp, os.path.basename(self._filesystem_path)))
  532. self._sync_directory(parent_dir)
  533. else:
  534. self._sync_directory(parent_dir)
  535. else:
  536. # Delete an item
  537. if not is_safe_filesystem_path_component(href):
  538. raise UnsafePathError(href)
  539. path = path_to_filesystem(self._filesystem_path, href)
  540. if not os.path.isfile(path):
  541. raise ComponentNotFoundError(href)
  542. os.remove(path)
  543. self._sync_directory(os.path.dirname(path))
  544. def get_meta(self, key):
  545. if os.path.exists(self._props_path):
  546. with open(self._props_path, encoding=self.encoding) as prop:
  547. return json.load(prop).get(key)
  548. def set_meta(self, props):
  549. if os.path.exists(self._props_path):
  550. with open(self._props_path, encoding=self.encoding) as prop:
  551. old_props = json.load(prop)
  552. old_props.update(props)
  553. props = old_props
  554. props = {key: value for key, value in props.items() if value}
  555. with self._atomic_write(self._props_path, "w+") as prop:
  556. json.dump(props, prop)
  557. @property
  558. def last_modified(self):
  559. last = max([os.path.getmtime(self._filesystem_path)] + [
  560. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  561. for filename in os.listdir(self._filesystem_path)] or [0])
  562. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  563. def serialize(self):
  564. if not os.path.exists(self._filesystem_path):
  565. return None
  566. items = []
  567. for href in os.listdir(self._filesystem_path):
  568. if not is_safe_filesystem_path_component(href):
  569. self.logger.debug("Skipping component: %s", href)
  570. continue
  571. path = os.path.join(self._filesystem_path, href)
  572. if os.path.isfile(path):
  573. self.logger.debug("Read object: %s", path)
  574. with open(path, encoding=self.encoding, newline="") as fd:
  575. items.append(vobject.readOne(fd.read()))
  576. if self.get_meta("tag") == "VCALENDAR":
  577. collection = vobject.iCalendar()
  578. for item in items:
  579. for content in ("vevent", "vtodo", "vjournal"):
  580. if content in item.contents:
  581. for item_part in getattr(item, "%s_list" % content):
  582. collection.add(item_part)
  583. break
  584. return collection.serialize()
  585. elif self.get_meta("tag") == "VADDRESSBOOK":
  586. return "".join([item.serialize() for item in items])
  587. return ""
  588. _lock = threading.Lock()
  589. _waiters = []
  590. _lock_file = None
  591. _lock_file_locked = False
  592. _readers = 0
  593. _writer = False
  594. @classmethod
  595. @contextmanager
  596. def acquire_lock(cls, mode, user=None):
  597. def condition():
  598. if mode == "r":
  599. return not cls._writer
  600. else:
  601. return not cls._writer and cls._readers == 0
  602. folder = os.path.expanduser(cls.configuration.get(
  603. "storage", "filesystem_folder"))
  604. # Use a primitive lock which only works within one process as a
  605. # precondition for inter-process file-based locking
  606. with cls._lock:
  607. if cls._waiters or not condition():
  608. # Use FIFO for access requests
  609. waiter = threading.Condition(lock=cls._lock)
  610. cls._waiters.append(waiter)
  611. while True:
  612. waiter.wait()
  613. if condition():
  614. break
  615. cls._waiters.pop(0)
  616. if mode == "r":
  617. cls._readers += 1
  618. # Notify additional potential readers
  619. if cls._waiters:
  620. cls._waiters[0].notify()
  621. else:
  622. cls._writer = True
  623. if not cls._lock_file:
  624. cls._makedirs_synced(folder)
  625. lock_path = os.path.join(folder, ".Radicale.lock")
  626. cls._lock_file = open(lock_path, "w+")
  627. # Set access rights to a necessary minimum to prevent locking
  628. # by arbitrary users
  629. try:
  630. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  631. except OSError:
  632. cls.logger.debug("Failed to set permissions on lock file")
  633. if not cls._lock_file_locked:
  634. if os.name == "nt":
  635. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  636. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  637. overlapped = Overlapped()
  638. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  639. cls.logger.debug("Locking not supported")
  640. elif os.name == "posix":
  641. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  642. try:
  643. fcntl.flock(cls._lock_file.fileno(), _cmd)
  644. except OSError:
  645. cls.logger.debug("Locking not supported")
  646. cls._lock_file_locked = True
  647. try:
  648. yield
  649. # execute hook
  650. hook = cls.configuration.get("storage", "hook")
  651. if mode == "w" and hook:
  652. cls.logger.debug("Running hook")
  653. subprocess.check_call(
  654. hook % {"user": shlex.quote(user or "Anonymous")},
  655. shell=True, cwd=folder)
  656. finally:
  657. with cls._lock:
  658. if mode == "r":
  659. cls._readers -= 1
  660. else:
  661. cls._writer = False
  662. if cls._readers == 0:
  663. if os.name == "nt":
  664. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  665. overlapped = Overlapped()
  666. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  667. cls.logger.debug("Unlocking not supported")
  668. elif os.name == "posix":
  669. try:
  670. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  671. except OSError:
  672. cls.logger.debug("Unlocking not supported")
  673. cls._lock_file_locked = False
  674. if cls._waiters:
  675. cls._waiters[0].notify()
  676. if (cls.configuration.getboolean(
  677. "storage", "filesystem_close_lock_file")
  678. and cls._readers == 0 and not cls._waiters):
  679. cls._lock_file.close()
  680. cls._lock_file = None