storage.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  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. Encoded as quoted-string (see RFC 2616).
  89. """
  90. etag = md5()
  91. etag.update(text.encode("utf-8"))
  92. return '"%s"' % etag.hexdigest()
  93. def get_uid(item):
  94. """UID value of an item if defined."""
  95. return hasattr(item, "uid") and item.uid.value
  96. def sanitize_path(path):
  97. """Make path absolute with leading slash to prevent access to other data.
  98. Preserve a potential trailing slash.
  99. """
  100. trailing_slash = "/" if path.endswith("/") else ""
  101. path = posixpath.normpath(path)
  102. new_path = "/"
  103. for part in path.split("/"):
  104. if not is_safe_path_component(part):
  105. continue
  106. new_path = posixpath.join(new_path, part)
  107. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  108. return new_path + trailing_slash
  109. def is_safe_path_component(path):
  110. """Check if path is a single component of a path.
  111. Check that the path is safe to join too.
  112. """
  113. return path and "/" not in path and path not in (".", "..")
  114. def is_safe_filesystem_path_component(path):
  115. """Check if path is a single component of a local and posix filesystem
  116. path.
  117. Check that the path is safe to join too.
  118. """
  119. return (
  120. path and not os.path.splitdrive(path)[0] and
  121. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  122. not path.startswith(".") and not path.endswith("~") and
  123. is_safe_path_component(path))
  124. def path_to_filesystem(root, *paths):
  125. """Convert path to a local filesystem path relative to base_folder.
  126. `root` must be a secure filesystem path, it will be prepend to the path.
  127. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  128. """
  129. paths = [sanitize_path(path).strip("/") for path in paths]
  130. safe_path = root
  131. for path in paths:
  132. if not path:
  133. continue
  134. for part in path.split("/"):
  135. if not is_safe_filesystem_path_component(part):
  136. raise UnsafePathError(part)
  137. safe_path = os.path.join(safe_path, part)
  138. return safe_path
  139. class UnsafePathError(ValueError):
  140. def __init__(self, path):
  141. message = "Can't translate name safely to filesystem: %s" % path
  142. super().__init__(message)
  143. class ComponentExistsError(ValueError):
  144. def __init__(self, path):
  145. message = "Component already exists: %s" % path
  146. super().__init__(message)
  147. class ComponentNotFoundError(ValueError):
  148. def __init__(self, path):
  149. message = "Component doesn't exist: %s" % path
  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. """Encoded as quoted-string (see RFC 2616)."""
  162. return get_etag(self.serialize())
  163. class BaseCollection:
  164. # Overriden on copy by the "load" function
  165. configuration = None
  166. logger = None
  167. def __init__(self, path, principal=False):
  168. """Initialize the collection.
  169. ``path`` must be the normalized relative path of the collection, using
  170. the slash as the folder delimiter, with no leading nor trailing slash.
  171. """
  172. raise NotImplementedError
  173. @classmethod
  174. def discover(cls, path, depth="0"):
  175. """Discover a list of collections under the given ``path``.
  176. If ``depth`` is "0", only the actual object under ``path`` is
  177. returned.
  178. If ``depth`` is anything but "0", it is considered as "1" and direct
  179. children are included in the result.
  180. The ``path`` is relative.
  181. The root collection "/" must always exist.
  182. """
  183. raise NotImplementedError
  184. @classmethod
  185. def move(cls, item, to_collection, to_href):
  186. """Move an object.
  187. ``item`` is the item to move.
  188. ``to_collection`` is the target collection.
  189. ``to_href`` is the target name in ``to_collection``. An item with the
  190. same name might already exist.
  191. """
  192. if item.collection.path == to_collection.path and item.href == to_href:
  193. return
  194. if to_collection.has(to_href):
  195. to_collection.update(to_href, item.item)
  196. else:
  197. to_collection.upload(to_href, item.item)
  198. item.collection.delete(item.href)
  199. @property
  200. def etag(self):
  201. """Encoded as quoted-string (see RFC 2616)."""
  202. return get_etag(self.serialize())
  203. @classmethod
  204. def create_collection(cls, href, collection=None, props=None):
  205. """Create a collection.
  206. If the collection already exists and neither ``collection`` nor
  207. ``props`` are set, this method shouldn't do anything. Otherwise the
  208. existing collection must be replaced.
  209. ``collection`` is a list of vobject components.
  210. ``props`` are metadata values for the collection.
  211. ``props["tag"]`` is the type of collection (VCALENDAR or
  212. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  213. collection.
  214. """
  215. raise NotImplementedError
  216. def list(self):
  217. """List collection items."""
  218. raise NotImplementedError
  219. def get(self, href):
  220. """Fetch a single item."""
  221. raise NotImplementedError
  222. def get_multi(self, hrefs):
  223. """Fetch multiple items. Duplicate hrefs must be ignored.
  224. Functionally similar to ``get``, but might bring performance benefits
  225. on some storages when used cleverly.
  226. """
  227. for href in set(hrefs):
  228. yield self.get(href)
  229. def pre_filtered_list(self, filters):
  230. """List collection items with optional pre filtering.
  231. This could largely improve performance of reports depending on
  232. the filters and this implementation.
  233. This returns all event by default
  234. """
  235. return [self.get(href) for href in self.list()]
  236. def has(self, href):
  237. """Check if an item exists by its href.
  238. Functionally similar to ``get``, but might bring performance benefits
  239. on some storages when used cleverly.
  240. """
  241. return self.get(href) is not None
  242. def upload(self, href, vobject_item):
  243. """Upload a new or replace an existing item."""
  244. raise NotImplementedError
  245. def delete(self, href=None):
  246. """Delete an item.
  247. When ``href`` is ``None``, delete the collection.
  248. """
  249. raise NotImplementedError
  250. def get_meta(self, key):
  251. """Get metadata value for collection."""
  252. raise NotImplementedError
  253. def set_meta(self, props):
  254. """Set metadata values for collection."""
  255. raise NotImplementedError
  256. @property
  257. def last_modified(self):
  258. """Get the HTTP-datetime of when the collection was modified."""
  259. raise NotImplementedError
  260. def serialize(self):
  261. """Get the unicode string representing the whole collection."""
  262. raise NotImplementedError
  263. @classmethod
  264. @contextmanager
  265. def acquire_lock(cls, mode, user=None):
  266. """Set a context manager to lock the whole storage.
  267. ``mode`` must either be "r" for shared access or "w" for exclusive
  268. access.
  269. ``user`` is the name of the logged in user or empty.
  270. """
  271. raise NotImplementedError
  272. class Collection(BaseCollection):
  273. """Collection stored in several files per calendar."""
  274. def __init__(self, path, principal=False, folder=None):
  275. if not folder:
  276. folder = self._get_collection_root_folder()
  277. # Path should already be sanitized
  278. self.path = sanitize_path(path).strip("/")
  279. self.encoding = self.configuration.get("encoding", "stock")
  280. self._filesystem_path = path_to_filesystem(folder, self.path)
  281. self._props_path = os.path.join(
  282. self._filesystem_path, ".Radicale.props")
  283. split_path = self.path.split("/")
  284. self.owner = split_path[0] if len(split_path) > 1 else None
  285. self.is_principal = principal
  286. @classmethod
  287. def _get_collection_root_folder(cls):
  288. filesystem_folder = os.path.expanduser(
  289. cls.configuration.get("storage", "filesystem_folder"))
  290. return os.path.join(filesystem_folder, "collection-root")
  291. @contextmanager
  292. def _atomic_write(self, path, mode="w", newline=None):
  293. directory = os.path.dirname(path)
  294. tmp = NamedTemporaryFile(
  295. mode=mode, dir=directory, encoding=self.encoding,
  296. delete=False, prefix=".Radicale.tmp-", newline=newline)
  297. try:
  298. yield tmp
  299. if self.configuration.getboolean("storage", "fsync"):
  300. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  301. fcntl.fcntl(tmp.fileno(), fcntl.F_FULLFSYNC)
  302. else:
  303. os.fsync(tmp.fileno())
  304. tmp.close()
  305. os.replace(tmp.name, path)
  306. except:
  307. tmp.close()
  308. os.remove(tmp.name)
  309. raise
  310. self._sync_directory(directory)
  311. @staticmethod
  312. def _find_available_file_name(exists_fn):
  313. # Prevent infinite loop
  314. for _ in range(10000):
  315. file_name = hex(getrandbits(32))[2:]
  316. if not exists_fn(file_name):
  317. return file_name
  318. raise FileExistsError(errno.EEXIST, "No usable file name found")
  319. @classmethod
  320. def _sync_directory(cls, path):
  321. """Sync directory to disk.
  322. This only works on POSIX and does nothing on other systems.
  323. """
  324. if not cls.configuration.getboolean("storage", "fsync"):
  325. return
  326. if os.name == "posix":
  327. fd = os.open(path, 0)
  328. try:
  329. if hasattr(fcntl, "F_FULLFSYNC"):
  330. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  331. else:
  332. os.fsync(fd)
  333. finally:
  334. os.close(fd)
  335. @classmethod
  336. def _makedirs_synced(cls, filesystem_path):
  337. """Recursively create a directory and its parents in a sync'ed way.
  338. This method acts silently when the folder already exists.
  339. """
  340. if os.path.isdir(filesystem_path):
  341. return
  342. parent_filesystem_path = os.path.dirname(filesystem_path)
  343. # Prevent infinite loop
  344. if filesystem_path != parent_filesystem_path:
  345. # Create parent dirs recursively
  346. cls._makedirs_synced(parent_filesystem_path)
  347. # Possible race!
  348. os.makedirs(filesystem_path, exist_ok=True)
  349. cls._sync_directory(parent_filesystem_path)
  350. @classmethod
  351. def discover(cls, path, depth="0"):
  352. if path is None:
  353. # Wrong URL
  354. return
  355. # Path should already be sanitized
  356. sane_path = sanitize_path(path).strip("/")
  357. attributes = sane_path.split("/")
  358. if not attributes[0]:
  359. attributes.pop()
  360. folder = cls._get_collection_root_folder()
  361. # Create the root collection
  362. cls._makedirs_synced(folder)
  363. try:
  364. filesystem_path = path_to_filesystem(folder, sane_path)
  365. except ValueError:
  366. # Path is unsafe
  367. return
  368. # Check if the path exists and if it leads to a collection or an item
  369. if not os.path.isdir(filesystem_path):
  370. if attributes and os.path.isfile(filesystem_path):
  371. href = attributes.pop()
  372. else:
  373. return
  374. else:
  375. href = None
  376. path = "/".join(attributes)
  377. principal = len(attributes) == 1
  378. collection = cls(path, principal)
  379. if href:
  380. yield collection.get(href)
  381. return
  382. yield collection
  383. if depth == "0":
  384. return
  385. for item in collection.list():
  386. yield collection.get(item)
  387. for href in os.listdir(filesystem_path):
  388. if not is_safe_filesystem_path_component(href):
  389. cls.logger.debug("Skipping collection: %s", href)
  390. continue
  391. child_filesystem_path = path_to_filesystem(filesystem_path, href)
  392. if os.path.isdir(child_filesystem_path):
  393. child_path = posixpath.join(path, href)
  394. child_principal = len(attributes) == 0
  395. yield cls(child_path, child_principal)
  396. @classmethod
  397. def create_collection(cls, href, collection=None, props=None):
  398. folder = cls._get_collection_root_folder()
  399. # Path should already be sanitized
  400. sane_path = sanitize_path(href).strip("/")
  401. attributes = sane_path.split("/")
  402. if not attributes[0]:
  403. attributes.pop()
  404. principal = len(attributes) == 1
  405. filesystem_path = path_to_filesystem(folder, sane_path)
  406. if not props:
  407. props = {}
  408. if not props.get("tag") and collection:
  409. props["tag"] = collection[0].name
  410. if not props:
  411. cls._makedirs_synced(filesystem_path)
  412. return cls(sane_path, principal=principal)
  413. parent_dir = os.path.dirname(filesystem_path)
  414. cls._makedirs_synced(parent_dir)
  415. # Create a temporary directory with an unsafe name
  416. with TemporaryDirectory(
  417. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  418. # The temporary directory itself can't be renamed
  419. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  420. os.makedirs(tmp_filesystem_path)
  421. self = cls("/", principal=principal, folder=tmp_filesystem_path)
  422. self.set_meta(props)
  423. if collection:
  424. if props.get("tag") == "VCALENDAR":
  425. collection, = collection
  426. items = []
  427. for content in ("vevent", "vtodo", "vjournal"):
  428. items.extend(
  429. getattr(collection, "%s_list" % content, []))
  430. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  431. vobject_items = {}
  432. for uid, items in items_by_uid:
  433. new_collection = vobject.iCalendar()
  434. for item in items:
  435. new_collection.add(item)
  436. href = self._find_available_file_name(vobject_items.get)
  437. vobject_items[href] = new_collection
  438. self.upload_all_nonatomic(vobject_items)
  439. elif props.get("tag") == "VCARD":
  440. vobject_items = {}
  441. for card in collection:
  442. href = self._find_available_file_name(vobject_items.get)
  443. vobject_items[href] = card
  444. self.upload_all_nonatomic(vobject_items)
  445. # This operation is not atomic on the filesystem level but it's
  446. # very unlikely that one rename operations succeeds while the
  447. # other fails or that only one gets written to disk.
  448. if os.path.exists(filesystem_path):
  449. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  450. os.rename(tmp_filesystem_path, filesystem_path)
  451. cls._sync_directory(parent_dir)
  452. return cls(sane_path, principal=principal)
  453. def upload_all_nonatomic(self, vobject_items):
  454. """Upload a new set of items.
  455. This takes a mapping of href and vobject items and
  456. uploads them nonatomic and without existence checks.
  457. """
  458. fs = []
  459. for href, item in vobject_items.items():
  460. path = path_to_filesystem(self._filesystem_path, href)
  461. fs.append(open(path, "w", encoding=self.encoding, newline=""))
  462. fs[-1].write(item.serialize())
  463. fsync_fn = lambda fd: None
  464. if self.configuration.getboolean("storage", "fsync"):
  465. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  466. fsync_fn = lambda fd: fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  467. else:
  468. fsync_fn = os.fsync
  469. # sync everything at once because it's slightly faster.
  470. for f in fs:
  471. fsync_fn(f.fileno())
  472. f.close()
  473. self._sync_directory(self._filesystem_path)
  474. @classmethod
  475. def move(cls, item, to_collection, to_href):
  476. os.replace(
  477. path_to_filesystem(item.collection._filesystem_path, item.href),
  478. path_to_filesystem(to_collection._filesystem_path, to_href))
  479. cls._sync_directory(to_collection._filesystem_path)
  480. if item.collection._filesystem_path != to_collection._filesystem_path:
  481. cls._sync_directory(item.collection._filesystem_path)
  482. def list(self):
  483. try:
  484. hrefs = os.listdir(self._filesystem_path)
  485. except IOError:
  486. return
  487. for href in hrefs:
  488. if not is_safe_filesystem_path_component(href):
  489. self.logger.debug("Skipping component: %s", href)
  490. continue
  491. path = os.path.join(self._filesystem_path, href)
  492. if os.path.isfile(path):
  493. yield href
  494. def get(self, href):
  495. if not href:
  496. return None
  497. href = href.strip("{}")
  498. if not is_safe_filesystem_path_component(href):
  499. self.logger.debug(
  500. "Can't translate name safely to filesystem: %s", href)
  501. return None
  502. path = path_to_filesystem(self._filesystem_path, href)
  503. if not os.path.isfile(path):
  504. return None
  505. with open(path, encoding=self.encoding, newline="") as fd:
  506. text = fd.read()
  507. last_modified = time.strftime(
  508. "%a, %d %b %Y %H:%M:%S GMT",
  509. time.gmtime(os.path.getmtime(path)))
  510. return Item(self, vobject.readOne(text), href, last_modified)
  511. def has(self, href):
  512. return self.get(href) is not None
  513. def upload(self, href, vobject_item):
  514. if not is_safe_filesystem_path_component(href):
  515. raise UnsafePathError(href)
  516. path = path_to_filesystem(self._filesystem_path, href)
  517. item = Item(self, vobject_item, href)
  518. with self._atomic_write(path, newline="") as fd:
  519. fd.write(item.serialize())
  520. return item
  521. def delete(self, href=None):
  522. if href is None:
  523. # Delete the collection
  524. if os.path.isdir(self._filesystem_path):
  525. parent_dir = os.path.dirname(self._filesystem_path)
  526. try:
  527. os.rmdir(self._filesystem_path)
  528. except OSError:
  529. with TemporaryDirectory(
  530. prefix=".Radicale.tmp-", dir=parent_dir) as tmp:
  531. os.rename(self._filesystem_path, os.path.join(
  532. tmp, os.path.basename(self._filesystem_path)))
  533. self._sync_directory(parent_dir)
  534. else:
  535. self._sync_directory(parent_dir)
  536. else:
  537. # Delete an item
  538. if not is_safe_filesystem_path_component(href):
  539. raise UnsafePathError(href)
  540. path = path_to_filesystem(self._filesystem_path, href)
  541. if not os.path.isfile(path):
  542. raise ComponentNotFoundError(href)
  543. os.remove(path)
  544. self._sync_directory(os.path.dirname(path))
  545. def get_meta(self, key):
  546. if os.path.exists(self._props_path):
  547. with open(self._props_path, encoding=self.encoding) as prop:
  548. return json.load(prop).get(key)
  549. def set_meta(self, props):
  550. if os.path.exists(self._props_path):
  551. with open(self._props_path, encoding=self.encoding) as prop:
  552. old_props = json.load(prop)
  553. old_props.update(props)
  554. props = old_props
  555. props = {key: value for key, value in props.items() if value}
  556. with self._atomic_write(self._props_path, "w+") as prop:
  557. json.dump(props, prop)
  558. @property
  559. def last_modified(self):
  560. last = max([os.path.getmtime(self._filesystem_path)] + [
  561. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  562. for filename in os.listdir(self._filesystem_path)] or [0])
  563. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  564. def serialize(self):
  565. if not os.path.exists(self._filesystem_path):
  566. return None
  567. items = []
  568. for href in os.listdir(self._filesystem_path):
  569. if not is_safe_filesystem_path_component(href):
  570. self.logger.debug("Skipping component: %s", href)
  571. continue
  572. path = os.path.join(self._filesystem_path, href)
  573. if os.path.isfile(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("storage", "close_lock_file")
  677. and cls._readers == 0 and not cls._waiters):
  678. cls._lock_file.close()
  679. cls._lock_file = None