storage.py 51 KB

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