storage.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 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 binascii
  24. import contextlib
  25. import json
  26. import os
  27. import pickle
  28. import posixpath
  29. import shlex
  30. import subprocess
  31. import sys
  32. import threading
  33. import time
  34. from contextlib import contextmanager
  35. from hashlib import md5
  36. from importlib import import_module
  37. from itertools import chain, groupby
  38. from random import getrandbits
  39. from tempfile import NamedTemporaryFile, TemporaryDirectory
  40. import vobject
  41. if sys.version_info >= (3, 5):
  42. # HACK: Avoid import cycle for Python < 3.5
  43. from . import xmlutils
  44. if os.name == "nt":
  45. import ctypes
  46. import ctypes.wintypes
  47. import msvcrt
  48. LOCKFILE_EXCLUSIVE_LOCK = 2
  49. if ctypes.sizeof(ctypes.c_void_p) == 4:
  50. ULONG_PTR = ctypes.c_uint32
  51. else:
  52. ULONG_PTR = ctypes.c_uint64
  53. class Overlapped(ctypes.Structure):
  54. _fields_ = [
  55. ("internal", ULONG_PTR),
  56. ("internal_high", ULONG_PTR),
  57. ("offset", ctypes.wintypes.DWORD),
  58. ("offset_high", ctypes.wintypes.DWORD),
  59. ("h_event", ctypes.wintypes.HANDLE)]
  60. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  61. lock_file_ex.argtypes = [
  62. ctypes.wintypes.HANDLE,
  63. ctypes.wintypes.DWORD,
  64. ctypes.wintypes.DWORD,
  65. ctypes.wintypes.DWORD,
  66. ctypes.wintypes.DWORD,
  67. ctypes.POINTER(Overlapped)]
  68. lock_file_ex.restype = ctypes.wintypes.BOOL
  69. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  70. unlock_file_ex.argtypes = [
  71. ctypes.wintypes.HANDLE,
  72. ctypes.wintypes.DWORD,
  73. ctypes.wintypes.DWORD,
  74. ctypes.wintypes.DWORD,
  75. ctypes.POINTER(Overlapped)]
  76. unlock_file_ex.restype = ctypes.wintypes.BOOL
  77. elif os.name == "posix":
  78. import fcntl
  79. def load(configuration, logger):
  80. """Load the storage manager chosen in configuration."""
  81. if sys.version_info < (3, 5):
  82. # HACK: Avoid import cycle for Python < 3.5
  83. global xmlutils
  84. from . import xmlutils
  85. storage_type = configuration.get("storage", "type")
  86. if storage_type == "multifilesystem":
  87. collection_class = Collection
  88. else:
  89. try:
  90. collection_class = import_module(storage_type).Collection
  91. except Exception as e:
  92. raise RuntimeError("Failed to load storage module %r: %s" %
  93. (storage_type, e)) from e
  94. logger.info("Storage type is %r", storage_type)
  95. class CollectionCopy(collection_class):
  96. """Collection copy, avoids overriding the original class attributes."""
  97. CollectionCopy.configuration = configuration
  98. CollectionCopy.logger = logger
  99. return CollectionCopy
  100. def check_item(vobject_item):
  101. """Check vobject items for common errors."""
  102. if vobject_item.name == "VCALENDAR":
  103. for component in vobject_item.components():
  104. if component.name not in ("VTODO", "VEVENT", "VJOURNAL"):
  105. continue
  106. if not get_uid(component):
  107. raise ValueError("UID in %s is missing" % component.name)
  108. # vobject interprets recurrence rules on demand
  109. try:
  110. component.rruleset
  111. except Exception as e:
  112. raise ValueError("invalid recurrence rules in %s" %
  113. component.name) from e
  114. elif vobject_item.name == "VCARD":
  115. if not get_uid(vobject_item):
  116. raise ValueError("UID in VCARD is missing")
  117. else:
  118. raise ValueError("Unknown item type: %r" % vobject_item.name)
  119. def scandir(path, only_dirs=False, only_files=False):
  120. """Iterator for directory elements. (For compatibility with Python < 3.5)
  121. ``only_dirs`` only return directories
  122. ``only_files`` only return files
  123. """
  124. if sys.version_info >= (3, 5):
  125. for entry in os.scandir(path):
  126. if ((not only_files or entry.is_file()) and
  127. (not only_dirs or entry.is_dir())):
  128. yield entry.name
  129. else:
  130. for name in os.listdir(path):
  131. p = os.path.join(path, name)
  132. if ((not only_files or os.path.isfile(p)) and
  133. (not only_dirs or os.path.isdir(p))):
  134. yield name
  135. def get_etag(text):
  136. """Etag from collection or item.
  137. Encoded as quoted-string (see RFC 2616).
  138. """
  139. etag = md5()
  140. etag.update(text.encode("utf-8"))
  141. return '"%s"' % etag.hexdigest()
  142. def get_uid(item):
  143. """UID value of an item if defined."""
  144. return (hasattr(item, "uid") or None) and item.uid.value
  145. def sanitize_path(path):
  146. """Make path absolute with leading slash to prevent access to other data.
  147. Preserve a potential trailing slash.
  148. """
  149. trailing_slash = "/" if path.endswith("/") else ""
  150. path = posixpath.normpath(path)
  151. new_path = "/"
  152. for part in path.split("/"):
  153. if not is_safe_path_component(part):
  154. continue
  155. new_path = posixpath.join(new_path, part)
  156. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  157. return new_path + trailing_slash
  158. def is_safe_path_component(path):
  159. """Check if path is a single component of a path.
  160. Check that the path is safe to join too.
  161. """
  162. return path and "/" not in path and path not in (".", "..")
  163. def is_safe_filesystem_path_component(path):
  164. """Check if path is a single component of a local and posix filesystem
  165. path.
  166. Check that the path is safe to join too.
  167. """
  168. return (
  169. path and not os.path.splitdrive(path)[0] and
  170. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  171. not path.startswith(".") and not path.endswith("~") and
  172. is_safe_path_component(path))
  173. def path_to_filesystem(root, *paths):
  174. """Convert path to a local filesystem path relative to base_folder.
  175. `root` must be a secure filesystem path, it will be prepend to the path.
  176. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  177. """
  178. paths = [sanitize_path(path).strip("/") for path in paths]
  179. safe_path = root
  180. for path in paths:
  181. if not path:
  182. continue
  183. for part in path.split("/"):
  184. if not is_safe_filesystem_path_component(part):
  185. raise UnsafePathError(part)
  186. safe_path_parent = safe_path
  187. safe_path = os.path.join(safe_path, part)
  188. # Check for conflicting files (e.g. case-insensitive file systems
  189. # or short names on Windows file systems)
  190. if (os.path.lexists(safe_path) and
  191. part not in scandir(safe_path_parent)):
  192. raise CollidingPathError(part)
  193. return safe_path
  194. class UnsafePathError(ValueError):
  195. def __init__(self, path):
  196. message = "Can't translate name safely to filesystem: %r" % path
  197. super().__init__(message)
  198. class CollidingPathError(ValueError):
  199. def __init__(self, path):
  200. message = "File name collision: %r" % path
  201. super().__init__(message)
  202. class ComponentExistsError(ValueError):
  203. def __init__(self, path):
  204. message = "Component already exists: %r" % path
  205. super().__init__(message)
  206. class ComponentNotFoundError(ValueError):
  207. def __init__(self, path):
  208. message = "Component doesn't exist: %r" % path
  209. super().__init__(message)
  210. class Item:
  211. def __init__(self, collection, item=None, href=None, last_modified=None,
  212. text=None, etag=None):
  213. """Initialize an item.
  214. ``collection`` the parent collection.
  215. ``href`` the href of the item.
  216. ``last_modified`` the HTTP-datetime of when the item was modified.
  217. ``text`` the text representation of the item (optional if ``item`` is
  218. set).
  219. ``item`` the vobject item (optional if ``text`` is set).
  220. ``etag`` the etag of the item (optional). See ``get_etag``.
  221. """
  222. if text is None and item is None:
  223. raise ValueError("at least one of 'text' or 'item' must be set")
  224. self.collection = collection
  225. self.href = href
  226. self.last_modified = last_modified
  227. self._text = text
  228. self._item = item
  229. self._etag = etag
  230. def __getattr__(self, attr):
  231. return getattr(self.item, attr)
  232. def serialize(self):
  233. if self._text is None:
  234. self._text = self.item.serialize()
  235. return self._text
  236. @property
  237. def item(self):
  238. if self._item is None:
  239. try:
  240. self._item = vobject.readOne(self._text)
  241. except Exception as e:
  242. raise RuntimeError("Failed to parse item %r in %r: %s" %
  243. (self.href, self.collection.path, e)) from e
  244. return self._item
  245. @property
  246. def etag(self):
  247. """Encoded as quoted-string (see RFC 2616)."""
  248. if self._etag is None:
  249. self._etag = get_etag(self.serialize())
  250. return self._etag
  251. class BaseCollection:
  252. # Overriden on copy by the "load" function
  253. configuration = None
  254. logger = None
  255. # Properties of instance
  256. """The sanitized path of the collection without leading or trailing ``/``.
  257. """
  258. path = ""
  259. """The owner of the collection. (``path.split("/", maxsplit=1)[0]``)"""
  260. owner = ""
  261. """Collection is a principal. (``bool(path) and "/" not in path``)"""
  262. is_principal = False
  263. @classmethod
  264. def discover(cls, path, depth="0"):
  265. """Discover a list of collections under the given ``path``.
  266. ``path`` is sanitized.
  267. If ``depth`` is "0", only the actual object under ``path`` is
  268. returned.
  269. If ``depth`` is anything but "0", it is considered as "1" and direct
  270. children are included in the result.
  271. The root collection "/" must always exist.
  272. """
  273. raise NotImplementedError
  274. @classmethod
  275. def move(cls, item, to_collection, to_href):
  276. """Move an object.
  277. ``item`` is the item to move.
  278. ``to_collection`` is the target collection.
  279. ``to_href`` is the target name in ``to_collection``. An item with the
  280. same name might already exist.
  281. """
  282. if item.collection.path == to_collection.path and item.href == to_href:
  283. return
  284. to_collection.upload(to_href, item.item)
  285. item.collection.delete(item.href)
  286. @property
  287. def etag(self):
  288. """Encoded as quoted-string (see RFC 2616)."""
  289. return get_etag(self.serialize())
  290. @classmethod
  291. def create_collection(cls, href, collection=None, props=None):
  292. """Create a collection.
  293. ``href`` is the sanitized path.
  294. If the collection already exists and neither ``collection`` nor
  295. ``props`` are set, this method shouldn't do anything. Otherwise the
  296. existing collection must be replaced.
  297. ``collection`` is a list of vobject components.
  298. ``props`` are metadata values for the collection.
  299. ``props["tag"]`` is the type of collection (VCALENDAR or
  300. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  301. collection.
  302. """
  303. raise NotImplementedError
  304. def sync(self, old_token=None):
  305. """Get the current sync token and changed items for synchronization.
  306. ``old_token`` an old sync token which is used as the base of the
  307. delta update. If sync token is missing, all items are returned.
  308. ValueError is raised for invalid or old tokens.
  309. WARNING: This simple default implementation treats all sync-token as
  310. invalid. It adheres to the specification but some clients
  311. (e.g. InfCloud) don't like it. Subclasses should provide a
  312. more sophisticated implementation.
  313. """
  314. token = "http://radicale.org/ns/sync/%s" % self.etag.strip("\"")
  315. if old_token:
  316. raise ValueError("Sync token are not supported")
  317. return token, self.list()
  318. def list(self):
  319. """List collection items."""
  320. raise NotImplementedError
  321. def get(self, href):
  322. """Fetch a single item."""
  323. raise NotImplementedError
  324. def get_multi(self, hrefs):
  325. """Fetch multiple items. Duplicate hrefs must be ignored.
  326. DEPRECATED: use ``get_multi2`` instead
  327. """
  328. return (self.get(href) for href in set(hrefs))
  329. def get_multi2(self, hrefs):
  330. """Fetch multiple items.
  331. Functionally similar to ``get``, but might bring performance benefits
  332. on some storages when used cleverly. It's not required to return the
  333. requested items in the correct order. Duplicated hrefs can be ignored.
  334. Returns tuples with the href and the item or None if the item doesn't
  335. exist.
  336. """
  337. return ((href, self.get(href)) for href in hrefs)
  338. def get_all(self):
  339. """Fetch all items.
  340. Functionally similar to ``get``, but might bring performance benefits
  341. on some storages when used cleverly.
  342. """
  343. return map(self.get, self.list())
  344. def get_all_filtered(self, filters):
  345. """Fetch all items with optional filtering.
  346. This can largely improve performance of reports depending on
  347. the filters and this implementation.
  348. Returns tuples in the form ``(item, filters_matched)``.
  349. ``filters_matched`` is a bool that indicates if ``filters`` are fully
  350. matched.
  351. This returns all events by default
  352. """
  353. return ((item, False) for item in self.get_all())
  354. def pre_filtered_list(self, filters):
  355. """List collection items with optional pre filtering.
  356. DEPRECATED: use ``get_all_filtered`` instead
  357. """
  358. return self.get_all()
  359. def has(self, href):
  360. """Check if an item exists by its href.
  361. Functionally similar to ``get``, but might bring performance benefits
  362. on some storages when used cleverly.
  363. """
  364. return self.get(href) is not None
  365. def upload(self, href, vobject_item):
  366. """Upload a new or replace an existing item."""
  367. raise NotImplementedError
  368. def delete(self, href=None):
  369. """Delete an item.
  370. When ``href`` is ``None``, delete the collection.
  371. """
  372. raise NotImplementedError
  373. def get_meta(self, key=None):
  374. """Get metadata value for collection.
  375. Return the value of the property ``key``. If ``key`` is ``None`` return
  376. a dict with all properties
  377. """
  378. raise NotImplementedError
  379. def set_meta(self, props):
  380. """Set metadata values for collection.
  381. ``props`` a dict with updates for properties. If a value is empty, the
  382. property must be deleted.
  383. """
  384. raise NotImplementedError
  385. @property
  386. def last_modified(self):
  387. """Get the HTTP-datetime of when the collection was modified."""
  388. raise NotImplementedError
  389. def serialize(self):
  390. """Get the unicode string representing the whole collection."""
  391. if self.get_meta("tag") == "VCALENDAR":
  392. collection = vobject.iCalendar()
  393. for item in self.get_all():
  394. for content in ("vevent", "vtodo", "vjournal"):
  395. for component in getattr(item, "%s_list" % content, ()):
  396. collection.add(component)
  397. return collection.serialize()
  398. elif self.get_meta("tag") == "VADDRESSBOOK":
  399. return "".join(item.serialize() for item in self.get_all())
  400. return ""
  401. @classmethod
  402. @contextmanager
  403. def acquire_lock(cls, mode, user=None):
  404. """Set a context manager to lock the whole storage.
  405. ``mode`` must either be "r" for shared access or "w" for exclusive
  406. access.
  407. ``user`` is the name of the logged in user or empty.
  408. """
  409. raise NotImplementedError
  410. class Collection(BaseCollection):
  411. """Collection stored in several files per calendar."""
  412. def __init__(self, path, principal=None, folder=None):
  413. # DEPRECATED: Remove useless principal attribute
  414. if folder is None:
  415. folder = self._get_collection_root_folder()
  416. # Path should already be sanitized
  417. self.path = sanitize_path(path).strip("/")
  418. self.encoding = self.configuration.get("encoding", "stock")
  419. self._filesystem_path = path_to_filesystem(folder, self.path)
  420. self._props_path = os.path.join(
  421. self._filesystem_path, ".Radicale.props")
  422. self.owner = self.path.split("/", maxsplit=1)[0]
  423. if principal is None:
  424. principal = bool(self.path) and "/" not in self.path
  425. self.is_principal = principal
  426. self._meta_cache = None
  427. self._etag_cache = None
  428. @classmethod
  429. def _get_collection_root_folder(cls):
  430. filesystem_folder = os.path.expanduser(
  431. cls.configuration.get("storage", "filesystem_folder"))
  432. return os.path.join(filesystem_folder, "collection-root")
  433. @contextmanager
  434. def _atomic_write(self, path, mode="w", newline=None):
  435. directory = os.path.dirname(path)
  436. tmp = NamedTemporaryFile(
  437. mode=mode, dir=directory, delete=False, prefix=".Radicale.tmp-",
  438. newline=newline, encoding=None if "b" in mode else self.encoding)
  439. try:
  440. yield tmp
  441. self._fsync(tmp.fileno())
  442. tmp.close()
  443. os.replace(tmp.name, path)
  444. except:
  445. tmp.close()
  446. os.remove(tmp.name)
  447. raise
  448. self._sync_directory(directory)
  449. @staticmethod
  450. def _find_available_file_name(exists_fn, suffix=""):
  451. # Prevent infinite loop
  452. for _ in range(1000):
  453. file_name = "%016x" % getrandbits(64) + suffix
  454. if not exists_fn(file_name):
  455. return file_name
  456. # something is wrong with the PRNG
  457. raise RuntimeError("No unique random sequence found")
  458. @classmethod
  459. def _fsync(cls, fd):
  460. if cls.configuration.getboolean("storage", "filesystem_fsync"):
  461. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  462. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  463. else:
  464. os.fsync(fd)
  465. @classmethod
  466. def _sync_directory(cls, path):
  467. """Sync directory to disk.
  468. This only works on POSIX and does nothing on other systems.
  469. """
  470. if not cls.configuration.getboolean("storage", "filesystem_fsync"):
  471. return
  472. if os.name == "posix":
  473. fd = os.open(path, 0)
  474. try:
  475. cls._fsync(fd)
  476. finally:
  477. os.close(fd)
  478. @classmethod
  479. def _makedirs_synced(cls, filesystem_path):
  480. """Recursively create a directory and its parents in a sync'ed way.
  481. This method acts silently when the folder already exists.
  482. """
  483. if os.path.isdir(filesystem_path):
  484. return
  485. parent_filesystem_path = os.path.dirname(filesystem_path)
  486. # Prevent infinite loop
  487. if filesystem_path != parent_filesystem_path:
  488. # Create parent dirs recursively
  489. cls._makedirs_synced(parent_filesystem_path)
  490. # Possible race!
  491. os.makedirs(filesystem_path, exist_ok=True)
  492. cls._sync_directory(parent_filesystem_path)
  493. @classmethod
  494. def discover(cls, path, depth="0"):
  495. # Path should already be sanitized
  496. sane_path = sanitize_path(path).strip("/")
  497. attributes = sane_path.split("/")
  498. if not attributes[0]:
  499. attributes.pop()
  500. folder = cls._get_collection_root_folder()
  501. # Create the root collection
  502. cls._makedirs_synced(folder)
  503. try:
  504. filesystem_path = path_to_filesystem(folder, sane_path)
  505. except ValueError as e:
  506. # Path is unsafe
  507. cls.logger.debug("Unsafe path %r requested from storage: %s",
  508. sane_path, e, exc_info=True)
  509. return
  510. # Check if the path exists and if it leads to a collection or an item
  511. if not os.path.isdir(filesystem_path):
  512. if attributes and os.path.isfile(filesystem_path):
  513. href = attributes.pop()
  514. else:
  515. return
  516. else:
  517. href = None
  518. sane_path = "/".join(attributes)
  519. collection = cls(sane_path)
  520. if href:
  521. yield collection.get(href)
  522. return
  523. yield collection
  524. if depth == "0":
  525. return
  526. for item in collection.list():
  527. yield collection.get(item)
  528. for href in scandir(filesystem_path, only_dirs=True):
  529. if not is_safe_filesystem_path_component(href):
  530. if not href.startswith(".Radicale"):
  531. cls.logger.debug("Skipping collection %r in %r", href,
  532. sane_path)
  533. continue
  534. child_path = posixpath.join(sane_path, href)
  535. yield cls(child_path)
  536. @classmethod
  537. def create_collection(cls, href, collection=None, props=None):
  538. folder = cls._get_collection_root_folder()
  539. # Path should already be sanitized
  540. sane_path = sanitize_path(href).strip("/")
  541. filesystem_path = path_to_filesystem(folder, sane_path)
  542. if not props:
  543. props = {}
  544. if not props.get("tag") and collection:
  545. props["tag"] = collection[0].name
  546. if not props:
  547. cls._makedirs_synced(filesystem_path)
  548. return cls(sane_path)
  549. parent_dir = os.path.dirname(filesystem_path)
  550. cls._makedirs_synced(parent_dir)
  551. # Create a temporary directory with an unsafe name
  552. with TemporaryDirectory(
  553. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  554. # The temporary directory itself can't be renamed
  555. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  556. os.makedirs(tmp_filesystem_path)
  557. self = cls("/", folder=tmp_filesystem_path)
  558. self.set_meta(props)
  559. if collection:
  560. if props.get("tag") == "VCALENDAR":
  561. collection, = collection
  562. items = []
  563. for content in ("vevent", "vtodo", "vjournal"):
  564. items.extend(
  565. getattr(collection, "%s_list" % content, []))
  566. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  567. vobject_items = {}
  568. for uid, items in items_by_uid:
  569. new_collection = vobject.iCalendar()
  570. for item in items:
  571. new_collection.add(item)
  572. # href must comply to is_safe_filesystem_path_component
  573. # and no file name collisions must exist between hrefs
  574. href = self._find_available_file_name(
  575. vobject_items.get, suffix=".ics")
  576. vobject_items[href] = new_collection
  577. self._upload_all_nonatomic(vobject_items)
  578. elif props.get("tag") == "VCARD":
  579. vobject_items = {}
  580. for card in collection:
  581. # href must comply to is_safe_filesystem_path_component
  582. # and no file name collisions must exist between hrefs
  583. href = self._find_available_file_name(
  584. vobject_items.get, suffix=".vcf")
  585. vobject_items[href] = card
  586. self._upload_all_nonatomic(vobject_items)
  587. # This operation is not atomic on the filesystem level but it's
  588. # very unlikely that one rename operations succeeds while the
  589. # other fails or that only one gets written to disk.
  590. if os.path.exists(filesystem_path):
  591. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  592. os.rename(tmp_filesystem_path, filesystem_path)
  593. cls._sync_directory(parent_dir)
  594. return cls(sane_path)
  595. def upload_all_nonatomic(self, vobject_items):
  596. """DEPRECATED: Use ``_upload_all_nonatomic``"""
  597. return self._upload_all_nonatomic(vobject_items)
  598. def _upload_all_nonatomic(self, vobject_items):
  599. """Upload a new set of items.
  600. This takes a mapping of href and vobject items and
  601. uploads them nonatomic and without existence checks.
  602. """
  603. with contextlib.ExitStack() as stack:
  604. fs = []
  605. for href, item in vobject_items.items():
  606. if not is_safe_filesystem_path_component(href):
  607. raise UnsafePathError(href)
  608. path = path_to_filesystem(self._filesystem_path, href)
  609. fs.append(stack.enter_context(
  610. open(path, "w", encoding=self.encoding, newline="")))
  611. fs[-1].write(item.serialize())
  612. # sync everything at once because it's slightly faster.
  613. for f in fs:
  614. self._fsync(f.fileno())
  615. self._sync_directory(self._filesystem_path)
  616. @classmethod
  617. def move(cls, item, to_collection, to_href):
  618. if not is_safe_filesystem_path_component(to_href):
  619. raise UnsafePathError(to_href)
  620. os.replace(
  621. path_to_filesystem(item.collection._filesystem_path, item.href),
  622. path_to_filesystem(to_collection._filesystem_path, to_href))
  623. cls._sync_directory(to_collection._filesystem_path)
  624. if item.collection._filesystem_path != to_collection._filesystem_path:
  625. cls._sync_directory(item.collection._filesystem_path)
  626. # Track the change
  627. to_collection._update_history_etag(to_href, item)
  628. item.collection._update_history_etag(item.href, None)
  629. to_collection._clean_history_cache()
  630. if item.collection._filesystem_path != to_collection._filesystem_path:
  631. item.collection._clean_history_cache()
  632. @classmethod
  633. def _clean_cache(cls, folder, names, max_age=None):
  634. """Delete all ``names`` in ``folder`` that are older than ``max_age``.
  635. """
  636. age_limit = time.time() - max_age if max_age is not None else None
  637. modified = False
  638. for name in names:
  639. if not is_safe_filesystem_path_component(name):
  640. continue
  641. if age_limit is not None:
  642. try:
  643. # Race: Another process might have deleted the file.
  644. mtime = os.path.getmtime(os.path.join(folder, name))
  645. except FileNotFoundError:
  646. continue
  647. if mtime > age_limit:
  648. continue
  649. cls.logger.debug("Found expired item in cache: %r", name)
  650. # Race: Another process might have deleted or locked the
  651. # file.
  652. try:
  653. os.remove(os.path.join(folder, name))
  654. except (FileNotFoundError, PermissionError):
  655. continue
  656. modified = True
  657. if modified:
  658. cls._sync_directory(folder)
  659. def _update_history_etag(self, href, item):
  660. """Updates and retrieves the history etag from the history cache.
  661. The history cache contains a file for each current and deleted item
  662. of the collection. These files contain the etag of the item (empty
  663. string for deleted items) and a history etag, which is a hash over
  664. the previous history etag and the etag separated by "/".
  665. """
  666. history_folder = os.path.join(self._filesystem_path,
  667. ".Radicale.cache", "history")
  668. try:
  669. with open(os.path.join(history_folder, href), "rb") as f:
  670. cache_etag, history_etag = pickle.load(f)
  671. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  672. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  673. self.logger.warning(
  674. "Failed to load history cache entry %r in %r: %s",
  675. href, self.path, e, exc_info=True)
  676. cache_etag = ""
  677. # Initialize with random data to prevent collisions with cleaned
  678. # expired items.
  679. history_etag = binascii.hexlify(os.urandom(16)).decode("ascii")
  680. etag = item.etag if item else ""
  681. if etag != cache_etag:
  682. self._makedirs_synced(history_folder)
  683. history_etag = get_etag(history_etag + "/" + etag).strip("\"")
  684. try:
  685. # Race: Other processes might have created and locked the file.
  686. with self._atomic_write(os.path.join(history_folder, href),
  687. "wb") as f:
  688. pickle.dump([etag, history_etag], f)
  689. except PermissionError:
  690. pass
  691. return history_etag
  692. def _get_deleted_history_hrefs(self):
  693. """Returns the hrefs of all deleted items that are still in the
  694. history cache."""
  695. history_folder = os.path.join(self._filesystem_path,
  696. ".Radicale.cache", "history")
  697. try:
  698. for href in scandir(history_folder):
  699. if not is_safe_filesystem_path_component(href):
  700. continue
  701. if os.path.isfile(os.path.join(self._filesystem_path, href)):
  702. continue
  703. yield href
  704. except FileNotFoundError:
  705. pass
  706. def _clean_history_cache(self):
  707. # Delete all expired cache entries of deleted items.
  708. history_folder = os.path.join(self._filesystem_path,
  709. ".Radicale.cache", "history")
  710. self._clean_cache(history_folder, self._get_deleted_history_hrefs(),
  711. max_age=self.configuration.getint(
  712. "storage", "max_sync_token_age"))
  713. def sync(self, old_token=None):
  714. # The sync token has the form http://radicale.org/ns/sync/TOKEN_NAME
  715. # where TOKEN_NAME is the md5 hash of all history etags of present and
  716. # past items of the collection.
  717. def check_token_name(token_name):
  718. if len(token_name) != 32:
  719. return False
  720. for c in token_name:
  721. if c not in "0123456789abcdef":
  722. return False
  723. return True
  724. old_token_name = None
  725. if old_token:
  726. # Extract the token name from the sync token
  727. if not old_token.startswith("http://radicale.org/ns/sync/"):
  728. raise ValueError("Malformed token: %r" % old_token)
  729. old_token_name = old_token[len("http://radicale.org/ns/sync/"):]
  730. if not check_token_name(old_token_name):
  731. raise ValueError("Malformed token: %r" % old_token)
  732. # Get the current state and sync-token of the collection.
  733. state = {}
  734. token_name_hash = md5()
  735. # Find the history of all existing and deleted items
  736. for href, item in chain(
  737. ((item.href, item) for item in self.get_all()),
  738. ((href, None) for href in self._get_deleted_history_hrefs())):
  739. history_etag = self._update_history_etag(href, item)
  740. state[href] = history_etag
  741. token_name_hash.update((href + "/" + history_etag).encode("utf-8"))
  742. token_name = token_name_hash.hexdigest()
  743. token = "http://radicale.org/ns/sync/%s" % token_name
  744. if token_name == old_token_name:
  745. # Nothing changed
  746. return token, ()
  747. token_folder = os.path.join(self._filesystem_path,
  748. ".Radicale.cache", "sync-token")
  749. token_path = os.path.join(token_folder, token_name)
  750. old_state = {}
  751. if old_token_name:
  752. # load the old token state
  753. old_token_path = os.path.join(token_folder, old_token_name)
  754. try:
  755. # Race: Another process might have deleted the file.
  756. with open(old_token_path, "rb") as f:
  757. old_state = pickle.load(f)
  758. except (FileNotFoundError, pickle.UnpicklingError,
  759. ValueError) as e:
  760. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  761. self.logger.warning(
  762. "Failed to load stored sync token %r in %r: %s",
  763. old_token_name, self.path, e, exc_info=True)
  764. # Delete the damaged file
  765. try:
  766. os.remove(old_token_path)
  767. except (FileNotFoundError, PermissionError):
  768. pass
  769. raise ValueError("Token not found: %r" % old_token)
  770. # write the new token state or update the modification time of
  771. # existing token state
  772. if not os.path.exists(token_path):
  773. self._makedirs_synced(token_folder)
  774. try:
  775. # Race: Other processes might have created and locked the file.
  776. with self._atomic_write(token_path, "wb") as f:
  777. pickle.dump(state, f)
  778. except PermissionError:
  779. pass
  780. else:
  781. # clean up old sync tokens and item cache
  782. self._clean_cache(token_folder, os.listdir(token_folder),
  783. max_age=self.configuration.getint(
  784. "storage", "max_sync_token_age"))
  785. self._clean_history_cache()
  786. else:
  787. # Try to update the modification time
  788. try:
  789. # Race: Another process might have deleted the file.
  790. os.utime(token_path)
  791. except FileNotFoundError:
  792. pass
  793. changes = []
  794. # Find all new, changed and deleted (that are still in the item cache)
  795. # items
  796. for href, history_etag in state.items():
  797. if history_etag != old_state.get(href):
  798. changes.append(href)
  799. # Find all deleted items that are no longer in the item cache
  800. for href, history_etag in old_state.items():
  801. if href not in state:
  802. changes.append(href)
  803. return token, changes
  804. def list(self):
  805. for href in scandir(self._filesystem_path, only_files=True):
  806. if not is_safe_filesystem_path_component(href):
  807. if not href.startswith(".Radicale"):
  808. self.logger.debug(
  809. "Skipping item %r in %r", href, self.path)
  810. continue
  811. yield href
  812. _item_cache_cleaned = False
  813. def get(self, href, verify_href=True):
  814. item, metadata = self._get_with_metadata(href, verify_href=verify_href)
  815. return item
  816. def _get_with_metadata(self, href, verify_href=True):
  817. """Like ``get`` but additonally returns the following metadata:
  818. tag, start, end: see ``xmlutils.find_tag_and_time_range``. If
  819. extraction of the metadata failed, the values are all ``None``."""
  820. if verify_href:
  821. try:
  822. if not is_safe_filesystem_path_component(href):
  823. raise UnsafePathError(href)
  824. path = path_to_filesystem(self._filesystem_path, href)
  825. except ValueError as e:
  826. self.logger.debug(
  827. "Can't translate name %r safely to filesystem in %r: %s",
  828. href, self.path, e, exc_info=True)
  829. return None, None
  830. else:
  831. path = os.path.join(self._filesystem_path, href)
  832. try:
  833. with open(path, "rb") as f:
  834. btext = f.read()
  835. except (FileNotFoundError, IsADirectoryError):
  836. return None, None
  837. # The hash of the component in the file system. This is used to check,
  838. # if the entry in the cache is still valid.
  839. input_hash = md5()
  840. input_hash.update(btext)
  841. input_hash = input_hash.hexdigest()
  842. cache_folder = os.path.join(self._filesystem_path, ".Radicale.cache",
  843. "item")
  844. try:
  845. with open(os.path.join(cache_folder, href), "rb") as f:
  846. cinput_hash, cetag, ctext, ctag, cstart, cend = pickle.load(f)
  847. except (FileNotFoundError, pickle.UnpicklingError, ValueError) as e:
  848. if isinstance(e, (pickle.UnpicklingError, ValueError)):
  849. self.logger.warning(
  850. "Failed to load item cache entry %r in %r: %s",
  851. href, self.path, e, exc_info=True)
  852. cinput_hash = cetag = ctext = ctag = cstart = cend = None
  853. vobject_item = None
  854. if input_hash != cinput_hash:
  855. try:
  856. vobject_item = Item(self, href=href,
  857. text=btext.decode(self.encoding)).item
  858. check_item(vobject_item)
  859. except Exception as e:
  860. raise RuntimeError("Failed to parse item %r from %r: %s" %
  861. (href, self.path, e)) from e
  862. # Serialize the object again, to normalize the text representation.
  863. # The storage may have been edited externally.
  864. ctext = vobject_item.serialize()
  865. cetag = get_etag(ctext)
  866. try:
  867. try:
  868. ctag, cstart, cend = xmlutils.find_tag_and_time_range(
  869. vobject_item)
  870. except xmlutils.VObjectBugException as e:
  871. # HACK: Extraction of metadata failed, because of bugs in
  872. # VObject.
  873. self.logger.warning(
  874. "Failed to find tag and time range of item %r from %r "
  875. "(Bug in VObject): %s", href, self.path, e,
  876. exc_info=True)
  877. ctag = xmlutils.find_tag(vobject_item)
  878. cstart = xmlutils.TIMESTAMP_MIN
  879. cend = xmlutils.TIMESTAMP_MAX
  880. except Exception as e:
  881. raise RuntimeError("Failed to find tag and time range of item "
  882. "%r from %r: %s" % (href, self.path,
  883. e)) from e
  884. self._makedirs_synced(cache_folder)
  885. try:
  886. # Race: Other processes might have created and locked the
  887. # file.
  888. with self._atomic_write(os.path.join(cache_folder, href),
  889. "wb") as f:
  890. pickle.dump((input_hash, cetag, ctext,
  891. ctag, cstart, cend), f)
  892. except PermissionError:
  893. pass
  894. # Clean cache entries (max once per request)
  895. # This happens once after new uploads, or if the data in the
  896. # file system was edited externally.
  897. if not self._item_cache_cleaned:
  898. self._item_cache_cleaned = True
  899. self._clean_cache(cache_folder, (
  900. href for href in scandir(cache_folder) if not
  901. os.path.isfile(os.path.join(self._filesystem_path, href))))
  902. last_modified = time.strftime(
  903. "%a, %d %b %Y %H:%M:%S GMT",
  904. time.gmtime(os.path.getmtime(path)))
  905. return Item(self, href=href, last_modified=last_modified, etag=cetag,
  906. text=ctext, item=vobject_item), (ctag, cstart, cend)
  907. def get_multi2(self, hrefs):
  908. # It's faster to check for file name collissions here, because
  909. # we only need to call os.listdir once.
  910. files = None
  911. for href in hrefs:
  912. if files is None:
  913. # List dir after hrefs returned one item, the iterator may be
  914. # empty and the for-loop is never executed.
  915. files = os.listdir(self._filesystem_path)
  916. path = os.path.join(self._filesystem_path, href)
  917. if (not is_safe_filesystem_path_component(href) or
  918. href not in files and os.path.lexists(path)):
  919. self.logger.debug(
  920. "Can't translate name safely to filesystem: %r", href)
  921. yield (href, None)
  922. else:
  923. yield (href, self.get(href, verify_href=False))
  924. def get_all(self):
  925. # We don't need to check for collissions, because the the file names
  926. # are from os.listdir.
  927. return (self.get(href, verify_href=False) for href in self.list())
  928. def get_all_filtered(self, filters):
  929. tag, start, end, simple = xmlutils.simplify_prefilters(filters)
  930. if not tag:
  931. # no filter
  932. yield from ((item, simple) for item in self.get_all())
  933. return
  934. for item, (itag, istart, iend) in (
  935. self._get_with_metadata(href, verify_href=False)
  936. for href in self.list()):
  937. if tag == itag and istart < end and iend > start:
  938. yield item, simple and (start <= istart or iend <= end)
  939. def upload(self, href, vobject_item):
  940. if not is_safe_filesystem_path_component(href):
  941. raise UnsafePathError(href)
  942. path = path_to_filesystem(self._filesystem_path, href)
  943. item = Item(self, href=href, item=vobject_item)
  944. with self._atomic_write(path, newline="") as fd:
  945. fd.write(item.serialize())
  946. # Track the change
  947. self._update_history_etag(href, item)
  948. self._clean_history_cache()
  949. return item
  950. def delete(self, href=None):
  951. if href is None:
  952. # Delete the collection
  953. parent_dir = os.path.dirname(self._filesystem_path)
  954. try:
  955. os.rmdir(self._filesystem_path)
  956. except OSError:
  957. with TemporaryDirectory(
  958. prefix=".Radicale.tmp-", dir=parent_dir) as tmp:
  959. os.rename(self._filesystem_path, os.path.join(
  960. tmp, os.path.basename(self._filesystem_path)))
  961. self._sync_directory(parent_dir)
  962. else:
  963. self._sync_directory(parent_dir)
  964. else:
  965. # Delete an item
  966. if not is_safe_filesystem_path_component(href):
  967. raise UnsafePathError(href)
  968. path = path_to_filesystem(self._filesystem_path, href)
  969. if not os.path.isfile(path):
  970. raise ComponentNotFoundError(href)
  971. os.remove(path)
  972. self._sync_directory(os.path.dirname(path))
  973. # Track the change
  974. self._update_history_etag(href, None)
  975. self._clean_history_cache()
  976. def get_meta(self, key=None):
  977. # reuse cached value if the storage is read-only
  978. if self._writer or self._meta_cache is None:
  979. try:
  980. with open(self._props_path, encoding=self.encoding) as f:
  981. self._meta_cache = json.load(f)
  982. except FileNotFoundError:
  983. self._meta_cache = {}
  984. except ValueError as e:
  985. raise RuntimeError("Failed to load properties of collect"
  986. "ion %r: %s" % (self.path, e)) from e
  987. return self._meta_cache.get(key) if key else self._meta_cache
  988. def set_meta(self, props):
  989. new_props = self.get_meta()
  990. new_props.update(props)
  991. for key in tuple(new_props.keys()):
  992. if not new_props[key]:
  993. del new_props[key]
  994. with self._atomic_write(self._props_path, "w") as f:
  995. json.dump(new_props, f)
  996. @property
  997. def last_modified(self):
  998. relevant_files = chain(
  999. (self._filesystem_path,),
  1000. (self._props_path,) if os.path.exists(self._props_path) else (),
  1001. (os.path.join(self._filesystem_path, h) for h in self.list()))
  1002. last = max(map(os.path.getmtime, relevant_files))
  1003. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  1004. def serialize(self):
  1005. # serialize collection
  1006. if self.get_meta("tag") == "VCALENDAR":
  1007. in_vcalendar = False
  1008. vtimezones = ""
  1009. included_tzids = set()
  1010. vtimezone = []
  1011. tzid = None
  1012. components = ""
  1013. # Concatenate all child elements of VCALENDAR from all items
  1014. # together, while preventing duplicated VTIMEZONE entries.
  1015. # VTIMEZONEs are only distinguished by their TZID, if different
  1016. # timezones share the same TZID this produces errornous ouput.
  1017. # VObject fails at this too.
  1018. for item in self.get_all():
  1019. depth = 0
  1020. for line in item.serialize().split("\r\n"):
  1021. if line.startswith("BEGIN:"):
  1022. depth += 1
  1023. if depth == 1 and line == "BEGIN:VCALENDAR":
  1024. in_vcalendar = True
  1025. elif in_vcalendar:
  1026. if depth == 1 and line.startswith("END:"):
  1027. in_vcalendar = False
  1028. if depth == 2 and line == "BEGIN:VTIMEZONE":
  1029. vtimezone.append(line)
  1030. elif vtimezone:
  1031. vtimezone.append(line)
  1032. if depth == 2 and line.startswith("TZID:"):
  1033. tzid = line[len("TZID:"):]
  1034. elif depth == 2 and line.startswith("END:"):
  1035. if tzid is None or tzid not in included_tzids:
  1036. if vtimezones:
  1037. vtimezones += "\r\n"
  1038. vtimezones += "\r\n".join(vtimezone)
  1039. included_tzids.add(tzid)
  1040. vtimezone.clear()
  1041. tzid = None
  1042. elif depth >= 2:
  1043. if components:
  1044. components += "\r\n"
  1045. components += line
  1046. if line.startswith("END:"):
  1047. depth -= 1
  1048. return "\r\n".join(filter(bool, (
  1049. "BEGIN:VCALENDAR",
  1050. "VERSION:2.0",
  1051. "PRODID:-//PYVOBJECT//NONSGML Version 1//EN",
  1052. vtimezones,
  1053. components,
  1054. "END:VCALENDAR")))
  1055. elif self.get_meta("tag") == "VADDRESSBOOK":
  1056. return "".join((item.serialize() for item in self.get_all()))
  1057. return ""
  1058. @property
  1059. def etag(self):
  1060. # reuse cached value if the storage is read-only
  1061. if self._writer or self._etag_cache is None:
  1062. etag = md5()
  1063. for item in self.get_all():
  1064. etag.update((item.href + "/" + item.etag).encode("utf-8"))
  1065. self._etag_cache = '"%s"' % etag.hexdigest()
  1066. return self._etag_cache
  1067. _lock = threading.Lock()
  1068. _waiters = []
  1069. _lock_file = None
  1070. _lock_file_locked = False
  1071. _readers = 0
  1072. _writer = False
  1073. @classmethod
  1074. @contextmanager
  1075. def acquire_lock(cls, mode, user=None):
  1076. def condition():
  1077. if mode == "r":
  1078. return not cls._writer
  1079. else:
  1080. return not cls._writer and cls._readers == 0
  1081. file_locking = cls.configuration.getboolean("storage",
  1082. "filesystem_locking")
  1083. folder = os.path.expanduser(cls.configuration.get(
  1084. "storage", "filesystem_folder"))
  1085. # Use a primitive lock which only works within one process as a
  1086. # precondition for inter-process file-based locking
  1087. with cls._lock:
  1088. if cls._waiters or not condition():
  1089. # Use FIFO for access requests
  1090. waiter = threading.Condition(lock=cls._lock)
  1091. cls._waiters.append(waiter)
  1092. while True:
  1093. waiter.wait()
  1094. if condition():
  1095. break
  1096. cls._waiters.pop(0)
  1097. if mode == "r":
  1098. cls._readers += 1
  1099. # Notify additional potential readers
  1100. if cls._waiters:
  1101. cls._waiters[0].notify()
  1102. else:
  1103. cls._writer = True
  1104. if not cls._lock_file:
  1105. cls._makedirs_synced(folder)
  1106. lock_path = os.path.join(folder, ".Radicale.lock")
  1107. cls._lock_file = open(lock_path, "w+")
  1108. if file_locking and not cls._lock_file_locked:
  1109. if os.name == "nt":
  1110. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  1111. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  1112. overlapped = Overlapped()
  1113. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  1114. raise RuntimeError("Locking the storage failed "
  1115. "(can be disabled in the config): "
  1116. "%s" % ctypes.FormatError())
  1117. elif os.name == "posix":
  1118. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  1119. try:
  1120. fcntl.flock(cls._lock_file.fileno(), _cmd)
  1121. except OSError as e:
  1122. raise RuntimeError("Locking the storage failed "
  1123. "(can be disabled in the config): "
  1124. "%s" % e) from e
  1125. else:
  1126. raise RuntimeError("Locking the storage failed "
  1127. "(can be disabled in the config): "
  1128. "Unsupported operating system")
  1129. cls._lock_file_locked = True
  1130. try:
  1131. yield
  1132. # execute hook
  1133. hook = cls.configuration.get("storage", "hook")
  1134. if mode == "w" and hook:
  1135. cls.logger.debug("Running hook")
  1136. subprocess.check_call(
  1137. hook % {"user": shlex.quote(user or "Anonymous")},
  1138. shell=True, cwd=folder)
  1139. finally:
  1140. with cls._lock:
  1141. if mode == "r":
  1142. cls._readers -= 1
  1143. else:
  1144. cls._writer = False
  1145. if file_locking and cls._readers == 0:
  1146. if os.name == "nt":
  1147. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  1148. overlapped = Overlapped()
  1149. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  1150. raise RuntimeError("Unlocking the storage failed: "
  1151. "%s" % ctypes.FormatError())
  1152. elif os.name == "posix":
  1153. try:
  1154. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  1155. except OSError as e:
  1156. raise RuntimeError("Unlocking the storage failed: "
  1157. "%s" % e) from e
  1158. else:
  1159. raise RuntimeError("Unlocking the storage failed: "
  1160. "Unsupported operating system")
  1161. cls._lock_file_locked = False
  1162. if cls._waiters:
  1163. cls._waiters[0].notify()
  1164. if (cls.configuration.getboolean(
  1165. "storage", "filesystem_close_lock_file") and
  1166. cls._readers == 0 and not cls._waiters):
  1167. cls._lock_file.close()
  1168. cls._lock_file = None