storage.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. ``collection`` is a list of vobject components.
  203. ``props`` are metadata values for the collection.
  204. ``props["tag"]`` is the type of collection (VCALENDAR or
  205. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  206. collection.
  207. """
  208. raise NotImplementedError
  209. def list(self):
  210. """List collection items."""
  211. raise NotImplementedError
  212. def get(self, href):
  213. """Fetch a single item."""
  214. raise NotImplementedError
  215. def get_multi(self, hrefs):
  216. """Fetch multiple items. Duplicate hrefs must be ignored.
  217. Functionally similar to ``get``, but might bring performance benefits
  218. on some storages when used cleverly.
  219. """
  220. for href in set(hrefs):
  221. yield self.get(href)
  222. def pre_filtered_list(self, filters):
  223. """List collection items with optional pre filtering.
  224. This could largely improve performance of reports depending on
  225. the filters and this implementation.
  226. This returns all event by default
  227. """
  228. return [self.get(href) for href, _ in self.list()]
  229. def has(self, href):
  230. """Check if an item exists by its href.
  231. Functionally similar to ``get``, but might bring performance benefits
  232. on some storages when used cleverly.
  233. """
  234. return self.get(href) is not None
  235. def upload(self, href, vobject_item):
  236. """Upload a new item."""
  237. raise NotImplementedError
  238. def update(self, href, vobject_item, etag=None):
  239. """Update an item.
  240. Functionally similar to ``delete`` plus ``upload``, but might bring
  241. performance benefits on some storages when used cleverly.
  242. """
  243. self.delete(href, etag)
  244. self.upload(href, vobject_item)
  245. def delete(self, href=None, etag=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):
  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. """
  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"):
  292. dir = os.path.dirname(path)
  293. tmp = NamedTemporaryFile(mode=mode, dir=dir, encoding=self.encoding,
  294. delete=False, prefix=".Radicale.tmp-")
  295. try:
  296. yield tmp
  297. if self.configuration.getboolean("storage", "fsync"):
  298. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  299. fcntl.fcntl(tmp.fileno(), fcntl.F_FULLFSYNC)
  300. else:
  301. os.fsync(tmp.fileno())
  302. tmp.close()
  303. os.rename(tmp.name, path)
  304. except:
  305. tmp.close()
  306. os.remove(tmp.name)
  307. raise
  308. self._sync_directory(dir)
  309. def _find_available_file_name(self):
  310. # Prevent infinite loop
  311. for _ in range(10000):
  312. file_name = hex(getrandbits(32))[2:]
  313. if not self.has(file_name):
  314. return file_name
  315. raise FileExistsError(errno.EEXIST, "No usable file name found")
  316. @classmethod
  317. def _sync_directory(cls, path):
  318. """Sync directory to disk.
  319. This only works on POSIX and does nothing on other systems.
  320. """
  321. if not cls.configuration.getboolean("storage", "fsync"):
  322. return
  323. if os.name == "posix":
  324. fd = os.open(path, 0)
  325. try:
  326. if hasattr(fcntl, "F_FULLFSYNC"):
  327. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  328. else:
  329. os.fsync(fd)
  330. finally:
  331. os.close(fd)
  332. @classmethod
  333. def _makedirs_synced(cls, filesystem_path):
  334. """Recursively create a directory and its parents in a sync'ed way.
  335. This method acts silently when the folder already exists.
  336. """
  337. if os.path.isdir(filesystem_path):
  338. return
  339. parent_filesystem_path = os.path.dirname(filesystem_path)
  340. # Prevent infinite loop
  341. if filesystem_path != parent_filesystem_path:
  342. # Create parent dirs recursively
  343. cls._makedirs_synced(parent_filesystem_path)
  344. # Possible race!
  345. os.makedirs(filesystem_path, exist_ok=True)
  346. cls._sync_directory(parent_filesystem_path)
  347. @classmethod
  348. def discover(cls, path, depth="0"):
  349. if path is None:
  350. # Wrong URL
  351. return
  352. # Path should already be sanitized
  353. sane_path = sanitize_path(path).strip("/")
  354. attributes = sane_path.split("/")
  355. if not attributes[0]:
  356. attributes.pop()
  357. folder = cls._get_collection_root_folder()
  358. # Create the root collection
  359. cls._makedirs_synced(folder)
  360. try:
  361. filesystem_path = path_to_filesystem(folder, sane_path)
  362. except ValueError:
  363. # Path is unsafe
  364. return
  365. # Check if the path exists and if it leads to a collection or an item
  366. if not os.path.isdir(filesystem_path):
  367. if attributes and os.path.isfile(filesystem_path):
  368. href = attributes.pop()
  369. else:
  370. return
  371. else:
  372. href = None
  373. path = "/".join(attributes)
  374. principal = len(attributes) == 1
  375. collection = cls(path, principal)
  376. if href:
  377. yield collection.get(href)
  378. return
  379. yield collection
  380. if depth == "0":
  381. return
  382. for item in collection.list():
  383. yield collection.get(item[0])
  384. for href in os.listdir(filesystem_path):
  385. if not is_safe_filesystem_path_component(href):
  386. cls.logger.debug("Skipping collection: %s", href)
  387. continue
  388. child_filesystem_path = path_to_filesystem(filesystem_path, href)
  389. if os.path.isdir(child_filesystem_path):
  390. child_path = posixpath.join(path, href)
  391. child_principal = len(attributes) == 0
  392. yield cls(child_path, child_principal)
  393. @classmethod
  394. def create_collection(cls, href, collection=None, props=None):
  395. folder = cls._get_collection_root_folder()
  396. # Path should already be sanitized
  397. sane_path = sanitize_path(href).strip("/")
  398. attributes = sane_path.split("/")
  399. if not attributes[0]:
  400. attributes.pop()
  401. principal = len(attributes) == 1
  402. filesystem_path = path_to_filesystem(folder, sane_path)
  403. if not props:
  404. props = {}
  405. if not props.get("tag") and collection:
  406. props["tag"] = collection[0].name
  407. if not props:
  408. cls._makedirs_synced(filesystem_path)
  409. return cls(sane_path, principal=principal)
  410. parent_dir = os.path.dirname(filesystem_path)
  411. cls._makedirs_synced(parent_dir)
  412. # Create a temporary directory with an unsafe name
  413. with TemporaryDirectory(
  414. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  415. # The temporary directory itself can't be renamed
  416. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  417. os.makedirs(tmp_filesystem_path)
  418. self = cls("/", principal=principal, folder=tmp_filesystem_path)
  419. self.set_meta(props)
  420. if collection:
  421. if props.get("tag") == "VCALENDAR":
  422. collection, = collection
  423. items = []
  424. for content in ("vevent", "vtodo", "vjournal"):
  425. items.extend(
  426. getattr(collection, "%s_list" % content, []))
  427. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  428. for uid, items in items_by_uid:
  429. new_collection = vobject.iCalendar()
  430. for item in items:
  431. new_collection.add(item)
  432. self.upload(
  433. self._find_available_file_name(), new_collection)
  434. elif props.get("tag") == "VCARD":
  435. for card in collection:
  436. self.upload(self._find_available_file_name(), card)
  437. os.rename(tmp_filesystem_path, filesystem_path)
  438. cls._sync_directory(parent_dir)
  439. return cls(sane_path, principal=principal)
  440. @classmethod
  441. def move(cls, item, to_collection, to_href):
  442. os.rename(
  443. path_to_filesystem(item.collection._filesystem_path, item.href),
  444. path_to_filesystem(to_collection._filesystem_path, to_href))
  445. cls._sync_directory(to_collection._filesystem_path)
  446. if item.collection._filesystem_path != to_collection._filesystem_path:
  447. cls._sync_directory(item.collection._filesystem_path)
  448. def list(self):
  449. try:
  450. hrefs = os.listdir(self._filesystem_path)
  451. except IOError:
  452. return
  453. for href in hrefs:
  454. if not is_safe_filesystem_path_component(href):
  455. self.logger.debug("Skipping component: %s", href)
  456. continue
  457. path = os.path.join(self._filesystem_path, href)
  458. if os.path.isfile(path):
  459. with open(path, encoding=self.encoding) as fd:
  460. yield href, get_etag(fd.read())
  461. def get(self, href):
  462. if not href:
  463. return None
  464. href = href.strip("{}").replace("/", "_")
  465. if not is_safe_filesystem_path_component(href):
  466. self.logger.debug(
  467. "Can't translate name safely to filesystem: %s", href)
  468. return None
  469. path = path_to_filesystem(self._filesystem_path, href)
  470. if not os.path.isfile(path):
  471. return None
  472. with open(path, encoding=self.encoding) as fd:
  473. text = fd.read()
  474. last_modified = time.strftime(
  475. "%a, %d %b %Y %H:%M:%S GMT",
  476. time.gmtime(os.path.getmtime(path)))
  477. return Item(self, vobject.readOne(text), href, last_modified)
  478. def has(self, href):
  479. return self.get(href) is not None
  480. def upload(self, href, vobject_item):
  481. if not is_safe_filesystem_path_component(href):
  482. raise UnsafePathError(href)
  483. path = path_to_filesystem(self._filesystem_path, href)
  484. if os.path.exists(path):
  485. raise ComponentExistsError(href)
  486. item = Item(self, vobject_item, href)
  487. with self._atomic_write(path) as fd:
  488. fd.write(item.serialize())
  489. return item
  490. def update(self, href, vobject_item, etag=None):
  491. if not is_safe_filesystem_path_component(href):
  492. raise UnsafePathError(href)
  493. path = path_to_filesystem(self._filesystem_path, href)
  494. if not os.path.isfile(path):
  495. raise ComponentNotFoundError(href)
  496. with open(path, encoding=self.encoding) as fd:
  497. text = fd.read()
  498. if etag and etag != get_etag(text):
  499. raise EtagMismatchError(etag, get_etag(text))
  500. item = Item(self, vobject_item, href)
  501. with self._atomic_write(path) as fd:
  502. fd.write(item.serialize())
  503. return item
  504. def delete(self, href=None, etag=None):
  505. if href is None:
  506. # Delete the collection
  507. if os.path.isdir(self._filesystem_path):
  508. parent_dir = os.path.dirname(self._filesystem_path)
  509. try:
  510. os.rmdir(self._filesystem_path)
  511. except OSError:
  512. with TemporaryDirectory(prefix=".Radicale.tmp-",
  513. dir=parent_dir) as tmp_dir:
  514. os.rename(self._filesystem_path, os.path.join(
  515. tmp_dir, os.path.basename(self._filesystem_path)))
  516. self._sync_directory(parent_dir)
  517. else:
  518. self._sync_directory(parent_dir)
  519. else:
  520. # Delete an item
  521. if not is_safe_filesystem_path_component(href):
  522. raise UnsafePathError(href)
  523. path = path_to_filesystem(self._filesystem_path, href)
  524. if not os.path.isfile(path):
  525. raise ComponentNotFoundError(href)
  526. with open(path, encoding=self.encoding) as fd:
  527. text = fd.read()
  528. if etag and etag != get_etag(text):
  529. raise EtagMismatchError(etag, get_etag(text))
  530. os.remove(path)
  531. self._sync_directory(os.path.dirname(path))
  532. def get_meta(self, key):
  533. if os.path.exists(self._props_path):
  534. with open(self._props_path, encoding=self.encoding) as prop:
  535. return json.load(prop).get(key)
  536. def set_meta(self, props):
  537. if os.path.exists(self._props_path):
  538. with open(self._props_path, encoding=self.encoding) as prop:
  539. old_props = json.load(prop)
  540. old_props.update(props)
  541. props = old_props
  542. props = {key: value for key, value in props.items() if value}
  543. with self._atomic_write(self._props_path, "w+") as prop:
  544. json.dump(props, prop)
  545. @property
  546. def last_modified(self):
  547. last = max([os.path.getmtime(self._filesystem_path)] + [
  548. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  549. for filename in os.listdir(self._filesystem_path)] or [0])
  550. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  551. def serialize(self):
  552. if not os.path.exists(self._filesystem_path):
  553. return None
  554. items = []
  555. for href in os.listdir(self._filesystem_path):
  556. if not is_safe_filesystem_path_component(href):
  557. self.logger.debug("Skipping component: %s", href)
  558. continue
  559. path = os.path.join(self._filesystem_path, href)
  560. if os.path.isfile(path):
  561. with open(path, encoding=self.encoding) as fd:
  562. items.append(vobject.readOne(fd.read()))
  563. if self.get_meta("tag") == "VCALENDAR":
  564. collection = vobject.iCalendar()
  565. for item in items:
  566. for content in ("vevent", "vtodo", "vjournal"):
  567. if content in item.contents:
  568. for item_part in getattr(item, "%s_list" % content):
  569. collection.add(item_part)
  570. break
  571. return collection.serialize()
  572. elif self.get_meta("tag") == "VADDRESSBOOK":
  573. return "".join([item.serialize() for item in items])
  574. return ""
  575. _lock = threading.Lock()
  576. _waiters = []
  577. _lock_file = None
  578. _lock_file_locked = False
  579. _readers = 0
  580. _writer = False
  581. @classmethod
  582. @contextmanager
  583. def acquire_lock(cls, mode):
  584. def condition():
  585. if mode == "r":
  586. return not cls._writer
  587. else:
  588. return not cls._writer and cls._readers == 0
  589. # Use a primitive lock which only works within one process as a
  590. # precondition for inter-process file-based locking
  591. with cls._lock:
  592. if cls._waiters or not condition():
  593. # Use FIFO for access requests
  594. waiter = threading.Condition(lock=cls._lock)
  595. cls._waiters.append(waiter)
  596. while True:
  597. waiter.wait()
  598. if condition():
  599. break
  600. cls._waiters.pop(0)
  601. if mode == "r":
  602. cls._readers += 1
  603. # Notify additional potential readers
  604. if cls._waiters:
  605. cls._waiters[0].notify()
  606. else:
  607. cls._writer = True
  608. if not cls._lock_file:
  609. folder = os.path.expanduser(
  610. cls.configuration.get("storage", "filesystem_folder"))
  611. cls._makedirs_synced(folder)
  612. lock_path = os.path.join(folder, ".Radicale.lock")
  613. cls._lock_file = open(lock_path, "w+")
  614. # Set access rights to a necessary minimum to prevent locking
  615. # by arbitrary users
  616. try:
  617. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  618. except OSError:
  619. cls.logger.debug("Failed to set permissions on lock file")
  620. if not cls._lock_file_locked:
  621. if os.name == "nt":
  622. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  623. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  624. overlapped = Overlapped()
  625. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  626. cls.logger.debug("Locking not supported")
  627. elif os.name == "posix":
  628. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  629. try:
  630. fcntl.flock(cls._lock_file.fileno(), _cmd)
  631. except OSError:
  632. cls.logger.debug("Locking not supported")
  633. cls._lock_file_locked = True
  634. try:
  635. yield
  636. finally:
  637. with cls._lock:
  638. if mode == "r":
  639. cls._readers -= 1
  640. else:
  641. cls._writer = False
  642. if cls._readers == 0:
  643. if os.name == "nt":
  644. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  645. overlapped = Overlapped()
  646. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  647. cls.logger.debug("Unlocking not supported")
  648. elif os.name == "posix":
  649. try:
  650. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  651. except OSError:
  652. cls.logger.debug("Unlocking not supported")
  653. cls._lock_file_locked = False
  654. if cls._waiters:
  655. cls._waiters[0].notify()