storage.py 52 KB

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