storage.py 27 KB

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