storage.py 52 KB

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