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 contextlib
  24. import errno
  25. import json
  26. import os
  27. import posixpath
  28. import shlex
  29. import stat
  30. import subprocess
  31. import threading
  32. import time
  33. import datetime
  34. from contextlib import contextmanager
  35. from hashlib import md5
  36. from importlib import import_module
  37. from itertools import groupby
  38. from random import getrandbits
  39. from tempfile import TemporaryDirectory, NamedTemporaryFile
  40. import vobject
  41. if os.name == "nt":
  42. import ctypes
  43. import ctypes.wintypes
  44. import msvcrt
  45. LOCKFILE_EXCLUSIVE_LOCK = 2
  46. if ctypes.sizeof(ctypes.c_void_p) == 4:
  47. ULONG_PTR = ctypes.c_uint32
  48. else:
  49. ULONG_PTR = ctypes.c_uint64
  50. class Overlapped(ctypes.Structure):
  51. _fields_ = [
  52. ("internal", ULONG_PTR),
  53. ("internal_high", ULONG_PTR),
  54. ("offset", ctypes.wintypes.DWORD),
  55. ("offset_high", ctypes.wintypes.DWORD),
  56. ("h_event", ctypes.wintypes.HANDLE)]
  57. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  58. lock_file_ex.argtypes = [
  59. ctypes.wintypes.HANDLE,
  60. ctypes.wintypes.DWORD,
  61. ctypes.wintypes.DWORD,
  62. ctypes.wintypes.DWORD,
  63. ctypes.wintypes.DWORD,
  64. ctypes.POINTER(Overlapped)]
  65. lock_file_ex.restype = ctypes.wintypes.BOOL
  66. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  67. unlock_file_ex.argtypes = [
  68. ctypes.wintypes.HANDLE,
  69. ctypes.wintypes.DWORD,
  70. ctypes.wintypes.DWORD,
  71. ctypes.wintypes.DWORD,
  72. ctypes.POINTER(Overlapped)]
  73. unlock_file_ex.restype = ctypes.wintypes.BOOL
  74. elif os.name == "posix":
  75. import fcntl
  76. def load(configuration, logger):
  77. """Load the storage manager chosen in configuration."""
  78. storage_type = configuration.get("storage", "type")
  79. if storage_type == "multifilesystem":
  80. collection_class = Collection
  81. else:
  82. collection_class = import_module(storage_type).Collection
  83. class CollectionCopy(collection_class):
  84. """Collection copy, avoids overriding the original class attributes."""
  85. CollectionCopy.configuration = configuration
  86. CollectionCopy.logger = logger
  87. return CollectionCopy
  88. def get_etag(text):
  89. """Etag from collection or item.
  90. Encoded as quoted-string (see RFC 2616).
  91. """
  92. etag = md5()
  93. etag.update(text.encode("utf-8"))
  94. return '"%s"' % etag.hexdigest()
  95. def get_uid(item):
  96. """UID value of an item if defined."""
  97. return hasattr(item, "uid") and item.uid.value
  98. def sanitize_path(path):
  99. """Make path absolute with leading slash to prevent access to other data.
  100. Preserve a potential trailing slash.
  101. """
  102. trailing_slash = "/" if path.endswith("/") else ""
  103. path = posixpath.normpath(path)
  104. new_path = "/"
  105. for part in path.split("/"):
  106. if not is_safe_path_component(part):
  107. continue
  108. new_path = posixpath.join(new_path, part)
  109. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  110. return new_path + trailing_slash
  111. def is_safe_path_component(path):
  112. """Check if path is a single component of a path.
  113. Check that the path is safe to join too.
  114. """
  115. return path and "/" not in path and path not in (".", "..")
  116. def is_safe_filesystem_path_component(path):
  117. """Check if path is a single component of a local and posix filesystem
  118. path.
  119. Check that the path is safe to join too.
  120. """
  121. return (
  122. path and not os.path.splitdrive(path)[0] and
  123. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  124. not path.startswith(".") and not path.endswith("~") and
  125. is_safe_path_component(path))
  126. def path_to_filesystem(root, *paths):
  127. """Convert path to a local filesystem path relative to base_folder.
  128. `root` must be a secure filesystem path, it will be prepend to the path.
  129. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  130. """
  131. paths = [sanitize_path(path).strip("/") for path in paths]
  132. safe_path = root
  133. for path in paths:
  134. if not path:
  135. continue
  136. for part in path.split("/"):
  137. if not is_safe_filesystem_path_component(part):
  138. raise UnsafePathError(part)
  139. safe_path = os.path.join(safe_path, part)
  140. return safe_path
  141. class UnsafePathError(ValueError):
  142. def __init__(self, path):
  143. message = "Can't translate name safely to filesystem: %s" % path
  144. super().__init__(message)
  145. class ComponentExistsError(ValueError):
  146. def __init__(self, path):
  147. message = "Component already exists: %s" % path
  148. super().__init__(message)
  149. class ComponentNotFoundError(ValueError):
  150. def __init__(self, path):
  151. message = "Component doesn't exist: %s" % path
  152. super().__init__(message)
  153. class Item:
  154. def __init__(self, collection, item, href, last_modified=None):
  155. self.collection = collection
  156. self.item = item
  157. self.href = href
  158. self.last_modified = last_modified
  159. def __getattr__(self, attr):
  160. return getattr(self.item, attr)
  161. @property
  162. def etag(self):
  163. """Encoded as quoted-string (see RFC 2616)."""
  164. return get_etag(self.serialize())
  165. class BaseCollection:
  166. # Overriden on copy by the "load" function
  167. configuration = None
  168. logger = None
  169. def __init__(self, path, principal=False):
  170. """Initialize the collection.
  171. ``path`` must be the normalized relative path of the collection, using
  172. the slash as the folder delimiter, with no leading nor trailing slash.
  173. """
  174. raise NotImplementedError
  175. @classmethod
  176. def discover(cls, path, depth="0"):
  177. """Discover a list of collections under the given ``path``.
  178. If ``depth`` is "0", only the actual object under ``path`` is
  179. returned.
  180. If ``depth`` is anything but "0", it is considered as "1" and direct
  181. children are included in the result.
  182. The ``path`` is relative.
  183. The root collection "/" must always exist.
  184. """
  185. raise NotImplementedError
  186. @classmethod
  187. def move(cls, item, to_collection, to_href):
  188. """Move an object.
  189. ``item`` is the item to move.
  190. ``to_collection`` is the target collection.
  191. ``to_href`` is the target name in ``to_collection``. An item with the
  192. same name might already exist.
  193. """
  194. if item.collection.path == to_collection.path and item.href == to_href:
  195. return
  196. to_collection.upload(to_href, item.item)
  197. item.collection.delete(item.href)
  198. @property
  199. def etag(self):
  200. """Encoded as quoted-string (see RFC 2616)."""
  201. return get_etag(self.serialize())
  202. @classmethod
  203. def create_collection(cls, href, collection=None, props=None):
  204. """Create a collection.
  205. If the collection already exists and neither ``collection`` nor
  206. ``props`` are set, this method shouldn't do anything. Otherwise the
  207. existing collection must be replaced.
  208. ``collection`` is a list of vobject components.
  209. ``props`` are metadata values for the collection.
  210. ``props["tag"]`` is the type of collection (VCALENDAR or
  211. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  212. collection.
  213. """
  214. raise NotImplementedError
  215. def list(self):
  216. """List collection items."""
  217. raise NotImplementedError
  218. def get(self, href):
  219. """Fetch a single item."""
  220. raise NotImplementedError
  221. def get_multi(self, hrefs):
  222. """Fetch multiple items. Duplicate hrefs must be ignored.
  223. Functionally similar to ``get``, but might bring performance benefits
  224. on some storages when used cleverly.
  225. """
  226. for href in set(hrefs):
  227. yield self.get(href)
  228. def pre_filtered_list(self, filters):
  229. """List collection items with optional pre filtering.
  230. This could largely improve performance of reports depending on
  231. the filters and this implementation.
  232. This returns all event by default
  233. """
  234. return [self.get(href) for href in self.list()]
  235. def has(self, href):
  236. """Check if an item exists by its href.
  237. Functionally similar to ``get``, but might bring performance benefits
  238. on some storages when used cleverly.
  239. """
  240. return self.get(href) is not None
  241. def upload(self, href, vobject_item):
  242. """Upload a new or replace an existing item."""
  243. raise NotImplementedError
  244. def delete(self, href=None):
  245. """Delete an item.
  246. When ``href`` is ``None``, delete the collection.
  247. """
  248. raise NotImplementedError
  249. def get_meta(self, key):
  250. """Get metadata value for collection."""
  251. raise NotImplementedError
  252. def set_meta(self, props):
  253. """Set metadata values for collection."""
  254. raise NotImplementedError
  255. @property
  256. def last_modified(self):
  257. """Get the HTTP-datetime of when the collection was modified."""
  258. raise NotImplementedError
  259. def serialize(self):
  260. """Get the unicode string representing the whole collection."""
  261. raise NotImplementedError
  262. @classmethod
  263. @contextmanager
  264. def acquire_lock(cls, mode, user=None):
  265. """Set a context manager to lock the whole storage.
  266. ``mode`` must either be "r" for shared access or "w" for exclusive
  267. access.
  268. ``user`` is the name of the logged in user or empty.
  269. """
  270. raise NotImplementedError
  271. class Collection(BaseCollection):
  272. """Collection stored in several files per calendar."""
  273. def __init__(self, path, principal=False, folder=None):
  274. if not folder:
  275. folder = self._get_collection_root_folder()
  276. # Path should already be sanitized
  277. self.path = sanitize_path(path).strip("/")
  278. self.encoding = self.configuration.get("encoding", "stock")
  279. self._filesystem_path = path_to_filesystem(folder, self.path)
  280. self._props_path = os.path.join(
  281. self._filesystem_path, ".Radicale.props")
  282. split_path = self.path.split("/")
  283. self.owner = split_path[0] if len(split_path) > 1 else None
  284. self.is_principal = principal
  285. @classmethod
  286. def _get_collection_root_folder(cls):
  287. filesystem_folder = os.path.expanduser(
  288. cls.configuration.get("storage", "filesystem_folder"))
  289. return os.path.join(filesystem_folder, "collection-root")
  290. @contextmanager
  291. def _atomic_write(self, path, mode="w", newline=None):
  292. directory = os.path.dirname(path)
  293. tmp = NamedTemporaryFile(
  294. mode=mode, dir=directory, encoding=self.encoding,
  295. delete=False, prefix=".Radicale.tmp-", newline=newline)
  296. try:
  297. yield tmp
  298. self._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 _fsync(cls, fd):
  316. if cls.configuration.getboolean("storage", "filesystem_fsync"):
  317. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  318. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  319. else:
  320. os.fsync(fd)
  321. @classmethod
  322. def _sync_directory(cls, path):
  323. """Sync directory to disk.
  324. This only works on POSIX and does nothing on other systems.
  325. """
  326. if not cls.configuration.getboolean("storage", "filesystem_fsync"):
  327. return
  328. if os.name == "posix":
  329. fd = os.open(path, 0)
  330. try:
  331. cls._fsync(fd)
  332. finally:
  333. os.close(fd)
  334. @classmethod
  335. def _makedirs_synced(cls, filesystem_path):
  336. """Recursively create a directory and its parents in a sync'ed way.
  337. This method acts silently when the folder already exists.
  338. """
  339. if os.path.isdir(filesystem_path):
  340. return
  341. parent_filesystem_path = os.path.dirname(filesystem_path)
  342. # Prevent infinite loop
  343. if filesystem_path != parent_filesystem_path:
  344. # Create parent dirs recursively
  345. cls._makedirs_synced(parent_filesystem_path)
  346. # Possible race!
  347. os.makedirs(filesystem_path, exist_ok=True)
  348. cls._sync_directory(parent_filesystem_path)
  349. @classmethod
  350. def discover(cls, path, depth="0"):
  351. if path is None:
  352. # Wrong URL
  353. return
  354. # Path should already be sanitized
  355. sane_path = sanitize_path(path).strip("/")
  356. attributes = sane_path.split("/")
  357. if not attributes[0]:
  358. attributes.pop()
  359. folder = cls._get_collection_root_folder()
  360. # Create the root collection
  361. cls._makedirs_synced(folder)
  362. try:
  363. filesystem_path = path_to_filesystem(folder, sane_path)
  364. except ValueError:
  365. # Path is unsafe
  366. return
  367. # Check if the path exists and if it leads to a collection or an item
  368. if not os.path.isdir(filesystem_path):
  369. if attributes and os.path.isfile(filesystem_path):
  370. href = attributes.pop()
  371. else:
  372. return
  373. else:
  374. href = None
  375. path = "/".join(attributes)
  376. principal = len(attributes) == 1
  377. collection = cls(path, principal)
  378. if href:
  379. yield collection.get(href)
  380. return
  381. yield collection
  382. if depth == "0":
  383. return
  384. for item in collection.list():
  385. yield collection.get(item)
  386. for href in os.listdir(filesystem_path):
  387. if not is_safe_filesystem_path_component(href):
  388. if not href.startswith(".Radicale"):
  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(
  437. vobject_items.get)
  438. vobject_items[href] = new_collection
  439. self.upload_all_nonatomic(vobject_items)
  440. elif props.get("tag") == "VCARD":
  441. vobject_items = {}
  442. for card in collection:
  443. href = self._find_available_file_name(
  444. vobject_items.get)
  445. vobject_items[href] = card
  446. self.upload_all_nonatomic(vobject_items)
  447. # This operation is not atomic on the filesystem level but it's
  448. # very unlikely that one rename operations succeeds while the
  449. # other fails or that only one gets written to disk.
  450. if os.path.exists(filesystem_path):
  451. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  452. os.rename(tmp_filesystem_path, filesystem_path)
  453. cls._sync_directory(parent_dir)
  454. return cls(sane_path, principal=principal)
  455. def upload_all_nonatomic(self, vobject_items):
  456. """Upload a new set of items.
  457. This takes a mapping of href and vobject items and
  458. uploads them nonatomic and without existence checks.
  459. """
  460. with contextlib.ExitStack() as stack:
  461. fs = []
  462. for href, item in vobject_items.items():
  463. if not is_safe_filesystem_path_component(href):
  464. raise UnsafePathError(href)
  465. path = path_to_filesystem(self._filesystem_path, href)
  466. fs.append(stack.enter_context(
  467. open(path, "w", encoding=self.encoding, newline="")))
  468. fs[-1].write(item.serialize())
  469. # sync everything at once because it's slightly faster.
  470. for f in fs:
  471. self._fsync(f.fileno())
  472. self._sync_directory(self._filesystem_path)
  473. @classmethod
  474. def move(cls, item, to_collection, to_href):
  475. if not is_safe_filesystem_path_component(to_href):
  476. raise UnsafePathError(to_href)
  477. os.replace(
  478. path_to_filesystem(item.collection._filesystem_path, item.href),
  479. path_to_filesystem(to_collection._filesystem_path, to_href))
  480. cls._sync_directory(to_collection._filesystem_path)
  481. if item.collection._filesystem_path != to_collection._filesystem_path:
  482. cls._sync_directory(item.collection._filesystem_path)
  483. def list(self):
  484. for href in os.listdir(self._filesystem_path):
  485. if not is_safe_filesystem_path_component(href):
  486. if not href.startswith(".Radicale"):
  487. self.logger.debug("Skipping component: %s", href)
  488. continue
  489. path = os.path.join(self._filesystem_path, href)
  490. if os.path.isfile(path):
  491. yield href
  492. def get(self, href):
  493. if not href:
  494. return None
  495. if not is_safe_filesystem_path_component(href):
  496. self.logger.debug(
  497. "Can't translate name safely to filesystem: %s", href)
  498. return None
  499. path = path_to_filesystem(self._filesystem_path, href)
  500. if not os.path.isfile(path):
  501. return None
  502. with open(path, encoding=self.encoding, newline="") as f:
  503. text = f.read()
  504. last_modified = time.strftime(
  505. "%a, %d %b %Y %H:%M:%S GMT",
  506. time.gmtime(os.path.getmtime(path)))
  507. try:
  508. item = vobject.readOne(text)
  509. except Exception:
  510. self.logger.error("Failed to parse component: %s", href)
  511. raise
  512. return Item(self, item, href, last_modified)
  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. 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=None):
  545. if os.path.exists(self._props_path):
  546. with open(self._props_path, encoding=self.encoding) as f:
  547. meta = json.load(f)
  548. return meta.get(key) if key else meta
  549. def set_meta(self, props):
  550. if os.path.exists(self._props_path):
  551. with open(self._props_path, encoding=self.encoding) as f:
  552. old_props = json.load(f)
  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 f:
  557. json.dump(props, f)
  558. @property
  559. def last_modified(self):
  560. relevant_files = [self._filesystem_path] + [
  561. path_to_filesystem(self._filesystem_path, href)
  562. for href in self.list()]
  563. if os.path.exists(self._props_path):
  564. relevant_files.append(self._props_path)
  565. last = max(map(os.path.getmtime, relevant_files))
  566. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  567. def serialize(self):
  568. items = []
  569. time_begin = datetime.datetime.now()
  570. for href in self.list():
  571. items.append(self.get(href).item)
  572. time_end = datetime.datetime.now()
  573. self.logger.info(
  574. "Collection read %d items in %s sec from %s", len(items),
  575. (time_end - time_begin).total_seconds(), self._filesystem_path)
  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