storage.py 28 KB

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