storage.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2016 Guillaume Ayoub
  4. #
  5. # This library is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This library is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  17. """
  18. Storage backends.
  19. This module loads the storage backend, according to the storage configuration.
  20. Default storage uses one folder per collection and one file per collection
  21. entry.
  22. """
  23. import errno
  24. import json
  25. import os
  26. import posixpath
  27. import shlex
  28. import stat
  29. import subprocess
  30. import threading
  31. import time
  32. from contextlib import contextmanager
  33. from hashlib import md5
  34. from importlib import import_module
  35. from itertools import groupby
  36. from random import getrandbits
  37. from tempfile import TemporaryDirectory, NamedTemporaryFile
  38. import vobject
  39. if os.name == "nt":
  40. import ctypes
  41. import ctypes.wintypes
  42. import msvcrt
  43. LOCKFILE_EXCLUSIVE_LOCK = 2
  44. if ctypes.sizeof(ctypes.c_void_p) == 4:
  45. ULONG_PTR = ctypes.c_uint32
  46. else:
  47. ULONG_PTR = ctypes.c_uint64
  48. class Overlapped(ctypes.Structure):
  49. _fields_ = [
  50. ("internal", ULONG_PTR),
  51. ("internal_high", ULONG_PTR),
  52. ("offset", ctypes.wintypes.DWORD),
  53. ("offset_high", ctypes.wintypes.DWORD),
  54. ("h_event", ctypes.wintypes.HANDLE)]
  55. lock_file_ex = ctypes.windll.kernel32.LockFileEx
  56. lock_file_ex.argtypes = [
  57. ctypes.wintypes.HANDLE,
  58. ctypes.wintypes.DWORD,
  59. ctypes.wintypes.DWORD,
  60. ctypes.wintypes.DWORD,
  61. ctypes.wintypes.DWORD,
  62. ctypes.POINTER(Overlapped)]
  63. lock_file_ex.restype = ctypes.wintypes.BOOL
  64. unlock_file_ex = ctypes.windll.kernel32.UnlockFileEx
  65. unlock_file_ex.argtypes = [
  66. ctypes.wintypes.HANDLE,
  67. ctypes.wintypes.DWORD,
  68. ctypes.wintypes.DWORD,
  69. ctypes.wintypes.DWORD,
  70. ctypes.POINTER(Overlapped)]
  71. unlock_file_ex.restype = ctypes.wintypes.BOOL
  72. elif os.name == "posix":
  73. import fcntl
  74. def load(configuration, logger):
  75. """Load the storage manager chosen in configuration."""
  76. storage_type = configuration.get("storage", "type")
  77. if storage_type == "multifilesystem":
  78. collection_class = Collection
  79. else:
  80. collection_class = import_module(storage_type).Collection
  81. class CollectionCopy(collection_class):
  82. """Collection copy, avoids overriding the original class attributes."""
  83. CollectionCopy.configuration = configuration
  84. CollectionCopy.logger = logger
  85. return CollectionCopy
  86. def get_etag(text):
  87. """Etag from collection or item.
  88. Encoded as quoted-string (see RFC 2616).
  89. """
  90. etag = md5()
  91. etag.update(text.encode("utf-8"))
  92. return '"%s"' % etag.hexdigest()
  93. def get_uid(item):
  94. """UID value of an item if defined."""
  95. return hasattr(item, "uid") and item.uid.value
  96. def sanitize_path(path):
  97. """Make path absolute with leading slash to prevent access to other data.
  98. Preserve a potential trailing slash.
  99. """
  100. trailing_slash = "/" if path.endswith("/") else ""
  101. path = posixpath.normpath(path)
  102. new_path = "/"
  103. for part in path.split("/"):
  104. if not part or part in (".", ".."):
  105. continue
  106. new_path = posixpath.join(new_path, part)
  107. trailing_slash = "" if new_path.endswith("/") else trailing_slash
  108. return new_path + trailing_slash
  109. def is_safe_path_component(path):
  110. """Check if path is a single component of a path.
  111. Check that the path is safe to join too.
  112. """
  113. return path and "/" not in path and path not in (".", "..")
  114. def is_safe_filesystem_path_component(path):
  115. """Check if path is a single component of a filesystem path.
  116. Check that the path is safe to join too.
  117. """
  118. return (
  119. path and not os.path.splitdrive(path)[0] and
  120. not os.path.split(path)[0] and path not in (os.curdir, os.pardir) and
  121. not path.startswith(".") and not path.endswith("~"))
  122. def path_to_filesystem(root, *paths):
  123. """Convert path to a local filesystem path relative to base_folder.
  124. `root` must be a secure filesystem path, it will be prepend to the path.
  125. Conversion of `paths` is done in a secure manner, or raises ``ValueError``.
  126. """
  127. paths = [sanitize_path(path).strip("/") for path in paths]
  128. safe_path = root
  129. for path in paths:
  130. if not path:
  131. continue
  132. for part in path.split("/"):
  133. if not is_safe_filesystem_path_component(part):
  134. raise UnsafePathError(part)
  135. safe_path = os.path.join(safe_path, part)
  136. return safe_path
  137. class UnsafePathError(ValueError):
  138. def __init__(self, path):
  139. message = "Can't translate name safely to filesystem: %s" % path
  140. super().__init__(message)
  141. class ComponentExistsError(ValueError):
  142. def __init__(self, path):
  143. message = "Component already exists: %s" % path
  144. super().__init__(message)
  145. class ComponentNotFoundError(ValueError):
  146. def __init__(self, path):
  147. message = "Component doesn't exist: %s" % path
  148. super().__init__(message)
  149. class EtagMismatchError(ValueError):
  150. def __init__(self, etag1, etag2):
  151. message = "ETags don't match: %s != %s" % (etag1, etag2)
  152. super().__init__(message)
  153. class Item:
  154. def __init__(self, collection, item, href, last_modified=None):
  155. self.collection = collection
  156. self.item = item
  157. self.href = href
  158. self.last_modified = last_modified
  159. def __getattr__(self, attr):
  160. return getattr(self.item, attr)
  161. @property
  162. def etag(self):
  163. """Encoded as quoted-string (see RFC 2616)."""
  164. return get_etag(self.serialize())
  165. class BaseCollection:
  166. # Overriden on copy by the "load" function
  167. configuration = None
  168. logger = None
  169. def __init__(self, path, principal=False):
  170. """Initialize the collection.
  171. ``path`` must be the normalized relative path of the collection, using
  172. the slash as the folder delimiter, with no leading nor trailing slash.
  173. """
  174. raise NotImplementedError
  175. @classmethod
  176. def discover(cls, path, depth="0"):
  177. """Discover a list of collections under the given ``path``.
  178. If ``depth`` is "0", only the actual object under ``path`` is
  179. returned.
  180. If ``depth`` is anything but "0", it is considered as "1" and direct
  181. children are included in the result.
  182. The ``path`` is relative.
  183. The root collection "/" must always exist.
  184. """
  185. raise NotImplementedError
  186. @classmethod
  187. def move(cls, item, to_collection, to_href):
  188. """Move an object.
  189. ``item`` is the item to move.
  190. ``to_collection`` is the target collection.
  191. ``to_href`` is the target name in ``to_collection``. An item with the
  192. same name might already exist.
  193. """
  194. if item.collection.path == to_collection.path and item.href == to_href:
  195. return
  196. if to_collection.has(to_href):
  197. to_collection.update(to_href, item.item)
  198. else:
  199. to_collection.upload(to_href, item.item)
  200. item.collection.delete(item.href)
  201. @property
  202. def etag(self):
  203. """Encoded as quoted-string (see RFC 2616)."""
  204. return get_etag(self.serialize())
  205. @classmethod
  206. def create_collection(cls, href, collection=None, props=None):
  207. """Create a collection.
  208. If the collection already exists and neither ``collection`` nor
  209. ``props`` are set, this method shouldn't do anything. Otherwise the
  210. existing collection must be replaced.
  211. ``collection`` is a list of vobject components.
  212. ``props`` are metadata values for the collection.
  213. ``props["tag"]`` is the type of collection (VCALENDAR or
  214. VADDRESSBOOK). If the key ``tag`` is missing, it is guessed from the
  215. collection.
  216. """
  217. raise NotImplementedError
  218. def list(self):
  219. """List collection items."""
  220. raise NotImplementedError
  221. def get(self, href):
  222. """Fetch a single item."""
  223. raise NotImplementedError
  224. def get_multi(self, hrefs):
  225. """Fetch multiple items. Duplicate hrefs must be ignored.
  226. Functionally similar to ``get``, but might bring performance benefits
  227. on some storages when used cleverly.
  228. """
  229. for href in set(hrefs):
  230. yield self.get(href)
  231. def pre_filtered_list(self, filters):
  232. """List collection items with optional pre filtering.
  233. This could largely improve performance of reports depending on
  234. the filters and this implementation.
  235. This returns all event by default
  236. """
  237. return [self.get(href) for href in self.list()]
  238. def has(self, href):
  239. """Check if an item exists by its href.
  240. Functionally similar to ``get``, but might bring performance benefits
  241. on some storages when used cleverly.
  242. """
  243. return self.get(href) is not None
  244. def upload(self, href, vobject_item):
  245. """Upload a new or replace an existing item."""
  246. raise NotImplementedError
  247. def delete(self, href=None):
  248. """Delete an item.
  249. When ``href`` is ``None``, delete the collection.
  250. """
  251. raise NotImplementedError
  252. def get_meta(self, key):
  253. """Get metadata value for collection."""
  254. raise NotImplementedError
  255. def set_meta(self, props):
  256. """Set metadata values for collection."""
  257. raise NotImplementedError
  258. @property
  259. def last_modified(self):
  260. """Get the HTTP-datetime of when the collection was modified."""
  261. raise NotImplementedError
  262. def serialize(self):
  263. """Get the unicode string representing the whole collection."""
  264. raise NotImplementedError
  265. @classmethod
  266. @contextmanager
  267. def acquire_lock(cls, mode, user=None):
  268. """Set a context manager to lock the whole storage.
  269. ``mode`` must either be "r" for shared access or "w" for exclusive
  270. access.
  271. ``user`` is the name of the logged in user or empty.
  272. """
  273. raise NotImplementedError
  274. class Collection(BaseCollection):
  275. """Collection stored in several files per calendar."""
  276. def __init__(self, path, principal=False, folder=None):
  277. if not folder:
  278. folder = self._get_collection_root_folder()
  279. # Path should already be sanitized
  280. self.path = sanitize_path(path).strip("/")
  281. self.encoding = self.configuration.get("encoding", "stock")
  282. self._filesystem_path = path_to_filesystem(folder, self.path)
  283. self._props_path = os.path.join(
  284. self._filesystem_path, ".Radicale.props")
  285. split_path = self.path.split("/")
  286. self.owner = split_path[0] if len(split_path) > 1 else None
  287. self.is_principal = principal
  288. @classmethod
  289. def _get_collection_root_folder(cls):
  290. filesystem_folder = os.path.expanduser(
  291. cls.configuration.get("storage", "filesystem_folder"))
  292. return os.path.join(filesystem_folder, "collection-root")
  293. @contextmanager
  294. def _atomic_write(self, path, mode="w", newline=None):
  295. directory = os.path.dirname(path)
  296. tmp = NamedTemporaryFile(
  297. mode=mode, dir=directory, encoding=self.encoding,
  298. delete=False, prefix=".Radicale.tmp-", newline=newline)
  299. try:
  300. yield tmp
  301. if self.configuration.getboolean("storage", "fsync"):
  302. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  303. fcntl.fcntl(tmp.fileno(), fcntl.F_FULLFSYNC)
  304. else:
  305. os.fsync(tmp.fileno())
  306. tmp.close()
  307. os.replace(tmp.name, path)
  308. except:
  309. tmp.close()
  310. os.remove(tmp.name)
  311. raise
  312. self._sync_directory(directory)
  313. @staticmethod
  314. def _find_available_file_name(exists_fn):
  315. # Prevent infinite loop
  316. for _ in range(10000):
  317. file_name = hex(getrandbits(32))[2:]
  318. if not exists_fn(file_name):
  319. return file_name
  320. raise FileExistsError(errno.EEXIST, "No usable file name found")
  321. @classmethod
  322. def _sync_directory(cls, path):
  323. """Sync directory to disk.
  324. This only works on POSIX and does nothing on other systems.
  325. """
  326. if not cls.configuration.getboolean("storage", "fsync"):
  327. return
  328. if os.name == "posix":
  329. fd = os.open(path, 0)
  330. try:
  331. if hasattr(fcntl, "F_FULLFSYNC"):
  332. fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  333. else:
  334. os.fsync(fd)
  335. finally:
  336. os.close(fd)
  337. @classmethod
  338. def _makedirs_synced(cls, filesystem_path):
  339. """Recursively create a directory and its parents in a sync'ed way.
  340. This method acts silently when the folder already exists.
  341. """
  342. if os.path.isdir(filesystem_path):
  343. return
  344. parent_filesystem_path = os.path.dirname(filesystem_path)
  345. # Prevent infinite loop
  346. if filesystem_path != parent_filesystem_path:
  347. # Create parent dirs recursively
  348. cls._makedirs_synced(parent_filesystem_path)
  349. # Possible race!
  350. os.makedirs(filesystem_path, exist_ok=True)
  351. cls._sync_directory(parent_filesystem_path)
  352. @classmethod
  353. def discover(cls, path, depth="0"):
  354. if path is None:
  355. # Wrong URL
  356. return
  357. # Path should already be sanitized
  358. sane_path = sanitize_path(path).strip("/")
  359. attributes = sane_path.split("/")
  360. if not attributes[0]:
  361. attributes.pop()
  362. folder = cls._get_collection_root_folder()
  363. # Create the root collection
  364. cls._makedirs_synced(folder)
  365. try:
  366. filesystem_path = path_to_filesystem(folder, sane_path)
  367. except ValueError:
  368. # Path is unsafe
  369. return
  370. # Check if the path exists and if it leads to a collection or an item
  371. if not os.path.isdir(filesystem_path):
  372. if attributes and os.path.isfile(filesystem_path):
  373. href = attributes.pop()
  374. else:
  375. return
  376. else:
  377. href = None
  378. path = "/".join(attributes)
  379. principal = len(attributes) == 1
  380. collection = cls(path, principal)
  381. if href:
  382. yield collection.get(href)
  383. return
  384. yield collection
  385. if depth == "0":
  386. return
  387. for item in collection.list():
  388. yield collection.get(item)
  389. for href in os.listdir(filesystem_path):
  390. if not is_safe_filesystem_path_component(href):
  391. cls.logger.debug("Skipping collection: %s", href)
  392. continue
  393. child_filesystem_path = path_to_filesystem(filesystem_path, href)
  394. if os.path.isdir(child_filesystem_path):
  395. child_path = posixpath.join(path, href)
  396. child_principal = len(attributes) == 0
  397. yield cls(child_path, child_principal)
  398. @classmethod
  399. def create_collection(cls, href, collection=None, props=None):
  400. folder = cls._get_collection_root_folder()
  401. # Path should already be sanitized
  402. sane_path = sanitize_path(href).strip("/")
  403. attributes = sane_path.split("/")
  404. if not attributes[0]:
  405. attributes.pop()
  406. principal = len(attributes) == 1
  407. filesystem_path = path_to_filesystem(folder, sane_path)
  408. if not props:
  409. props = {}
  410. if not props.get("tag") and collection:
  411. props["tag"] = collection[0].name
  412. if not props:
  413. cls._makedirs_synced(filesystem_path)
  414. return cls(sane_path, principal=principal)
  415. parent_dir = os.path.dirname(filesystem_path)
  416. cls._makedirs_synced(parent_dir)
  417. # Create a temporary directory with an unsafe name
  418. with TemporaryDirectory(
  419. prefix=".Radicale.tmp-", dir=parent_dir) as tmp_dir:
  420. # The temporary directory itself can't be renamed
  421. tmp_filesystem_path = os.path.join(tmp_dir, "collection")
  422. os.makedirs(tmp_filesystem_path)
  423. self = cls("/", principal=principal, folder=tmp_filesystem_path)
  424. self.set_meta(props)
  425. if collection:
  426. if props.get("tag") == "VCALENDAR":
  427. collection, = collection
  428. items = []
  429. for content in ("vevent", "vtodo", "vjournal"):
  430. items.extend(
  431. getattr(collection, "%s_list" % content, []))
  432. items_by_uid = groupby(sorted(items, key=get_uid), get_uid)
  433. vobject_items = {}
  434. for uid, items in items_by_uid:
  435. new_collection = vobject.iCalendar()
  436. for item in items:
  437. new_collection.add(item)
  438. href = self._find_available_file_name(vobject_items.get)
  439. vobject_items[href] = new_collection
  440. self.upload_all_nonatomic(vobject_items)
  441. elif props.get("tag") == "VCARD":
  442. vobject_items = {}
  443. for card in collection:
  444. href = self._find_available_file_name(vobject_items.get)
  445. vobject_items[href] = card
  446. self.upload_all_nonatomic(vobject_items)
  447. # This operation is not atomic on the filesystem level but it's
  448. # very unlikely that one rename operations succeeds while the
  449. # other fails or that only one gets written to disk.
  450. if os.path.exists(filesystem_path):
  451. os.rename(filesystem_path, os.path.join(tmp_dir, "delete"))
  452. os.rename(tmp_filesystem_path, filesystem_path)
  453. cls._sync_directory(parent_dir)
  454. return cls(sane_path, principal=principal)
  455. def upload_all_nonatomic(self, vobject_items):
  456. """Upload a new set of items.
  457. This takes a mapping of href and vobject items and
  458. uploads them nonatomic and without existence checks.
  459. """
  460. fs = []
  461. for href, item in vobject_items.items():
  462. path = path_to_filesystem(self._filesystem_path, href)
  463. fs.append(open(path, "w", encoding=self.encoding, newline=""))
  464. fs[-1].write(item.serialize())
  465. fsync_fn = lambda fd: None
  466. if self.configuration.getboolean("storage", "fsync"):
  467. if os.name == "posix" and hasattr(fcntl, "F_FULLFSYNC"):
  468. fsync_fn = lambda fd: fcntl.fcntl(fd, fcntl.F_FULLFSYNC)
  469. else:
  470. fsync_fn = os.fsync
  471. # sync everything at once because it's slightly faster.
  472. for f in fs:
  473. fsync_fn(f.fileno())
  474. f.close()
  475. self._sync_directory(self._filesystem_path)
  476. @classmethod
  477. def move(cls, item, to_collection, to_href):
  478. os.replace(
  479. path_to_filesystem(item.collection._filesystem_path, item.href),
  480. path_to_filesystem(to_collection._filesystem_path, to_href))
  481. cls._sync_directory(to_collection._filesystem_path)
  482. if item.collection._filesystem_path != to_collection._filesystem_path:
  483. cls._sync_directory(item.collection._filesystem_path)
  484. def list(self):
  485. try:
  486. hrefs = os.listdir(self._filesystem_path)
  487. except IOError:
  488. return
  489. for href in hrefs:
  490. if not is_safe_filesystem_path_component(href):
  491. self.logger.debug("Skipping component: %s", href)
  492. continue
  493. path = os.path.join(self._filesystem_path, href)
  494. if os.path.isfile(path):
  495. yield href
  496. def get(self, href):
  497. if not href:
  498. return None
  499. href = href.strip("{}").replace("/", "_")
  500. if not is_safe_filesystem_path_component(href):
  501. self.logger.debug(
  502. "Can't translate name safely to filesystem: %s", href)
  503. return None
  504. path = path_to_filesystem(self._filesystem_path, href)
  505. if not os.path.isfile(path):
  506. return None
  507. with open(path, encoding=self.encoding, newline="") as fd:
  508. text = fd.read()
  509. last_modified = time.strftime(
  510. "%a, %d %b %Y %H:%M:%S GMT",
  511. time.gmtime(os.path.getmtime(path)))
  512. return Item(self, vobject.readOne(text), href, last_modified)
  513. def has(self, href):
  514. return self.get(href) is not None
  515. def upload(self, href, vobject_item):
  516. if not is_safe_filesystem_path_component(href):
  517. raise UnsafePathError(href)
  518. path = path_to_filesystem(self._filesystem_path, href)
  519. item = Item(self, vobject_item, href)
  520. with self._atomic_write(path, newline="") as fd:
  521. fd.write(item.serialize())
  522. return item
  523. def delete(self, href=None):
  524. if href is None:
  525. # Delete the collection
  526. if os.path.isdir(self._filesystem_path):
  527. parent_dir = os.path.dirname(self._filesystem_path)
  528. try:
  529. os.rmdir(self._filesystem_path)
  530. except OSError:
  531. with TemporaryDirectory(
  532. prefix=".Radicale.tmp-", dir=parent_dir) as tmp:
  533. os.rename(self._filesystem_path, os.path.join(
  534. tmp, os.path.basename(self._filesystem_path)))
  535. self._sync_directory(parent_dir)
  536. else:
  537. self._sync_directory(parent_dir)
  538. else:
  539. # Delete an item
  540. if not is_safe_filesystem_path_component(href):
  541. raise UnsafePathError(href)
  542. path = path_to_filesystem(self._filesystem_path, href)
  543. if not os.path.isfile(path):
  544. raise ComponentNotFoundError(href)
  545. os.remove(path)
  546. self._sync_directory(os.path.dirname(path))
  547. def get_meta(self, key):
  548. if os.path.exists(self._props_path):
  549. with open(self._props_path, encoding=self.encoding) as prop:
  550. return json.load(prop).get(key)
  551. def set_meta(self, props):
  552. if os.path.exists(self._props_path):
  553. with open(self._props_path, encoding=self.encoding) as prop:
  554. old_props = json.load(prop)
  555. old_props.update(props)
  556. props = old_props
  557. props = {key: value for key, value in props.items() if value}
  558. with self._atomic_write(self._props_path, "w+") as prop:
  559. json.dump(props, prop)
  560. @property
  561. def last_modified(self):
  562. last = max([os.path.getmtime(self._filesystem_path)] + [
  563. os.path.getmtime(os.path.join(self._filesystem_path, filename))
  564. for filename in os.listdir(self._filesystem_path)] or [0])
  565. return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(last))
  566. def serialize(self):
  567. if not os.path.exists(self._filesystem_path):
  568. return None
  569. items = []
  570. for href in os.listdir(self._filesystem_path):
  571. if not is_safe_filesystem_path_component(href):
  572. self.logger.debug("Skipping component: %s", href)
  573. continue
  574. path = os.path.join(self._filesystem_path, href)
  575. if os.path.isfile(path):
  576. with open(path, encoding=self.encoding, newline="") as fd:
  577. items.append(vobject.readOne(fd.read()))
  578. if self.get_meta("tag") == "VCALENDAR":
  579. collection = vobject.iCalendar()
  580. for item in items:
  581. for content in ("vevent", "vtodo", "vjournal"):
  582. if content in item.contents:
  583. for item_part in getattr(item, "%s_list" % content):
  584. collection.add(item_part)
  585. break
  586. return collection.serialize()
  587. elif self.get_meta("tag") == "VADDRESSBOOK":
  588. return "".join([item.serialize() for item in items])
  589. return ""
  590. _lock = threading.Lock()
  591. _waiters = []
  592. _lock_file = None
  593. _lock_file_locked = False
  594. _readers = 0
  595. _writer = False
  596. @classmethod
  597. @contextmanager
  598. def acquire_lock(cls, mode, user=None):
  599. def condition():
  600. if mode == "r":
  601. return not cls._writer
  602. else:
  603. return not cls._writer and cls._readers == 0
  604. folder = os.path.expanduser(cls.configuration.get(
  605. "storage", "filesystem_folder"))
  606. # Use a primitive lock which only works within one process as a
  607. # precondition for inter-process file-based locking
  608. with cls._lock:
  609. if cls._waiters or not condition():
  610. # Use FIFO for access requests
  611. waiter = threading.Condition(lock=cls._lock)
  612. cls._waiters.append(waiter)
  613. while True:
  614. waiter.wait()
  615. if condition():
  616. break
  617. cls._waiters.pop(0)
  618. if mode == "r":
  619. cls._readers += 1
  620. # Notify additional potential readers
  621. if cls._waiters:
  622. cls._waiters[0].notify()
  623. else:
  624. cls._writer = True
  625. if not cls._lock_file:
  626. cls._makedirs_synced(folder)
  627. lock_path = os.path.join(folder, ".Radicale.lock")
  628. cls._lock_file = open(lock_path, "w+")
  629. # Set access rights to a necessary minimum to prevent locking
  630. # by arbitrary users
  631. try:
  632. os.chmod(lock_path, stat.S_IWUSR | stat.S_IRUSR)
  633. except OSError:
  634. cls.logger.debug("Failed to set permissions on lock file")
  635. if not cls._lock_file_locked:
  636. if os.name == "nt":
  637. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  638. flags = LOCKFILE_EXCLUSIVE_LOCK if mode == "w" else 0
  639. overlapped = Overlapped()
  640. if not lock_file_ex(handle, flags, 0, 1, 0, overlapped):
  641. cls.logger.debug("Locking not supported")
  642. elif os.name == "posix":
  643. _cmd = fcntl.LOCK_EX if mode == "w" else fcntl.LOCK_SH
  644. try:
  645. fcntl.flock(cls._lock_file.fileno(), _cmd)
  646. except OSError:
  647. cls.logger.debug("Locking not supported")
  648. cls._lock_file_locked = True
  649. try:
  650. yield
  651. # execute hook
  652. hook = cls.configuration.get("storage", "hook")
  653. if mode == "w" and hook:
  654. cls.logger.debug("Running hook")
  655. subprocess.check_call(
  656. hook % {"user": shlex.quote(user or "Anonymous")},
  657. shell=True, cwd=folder)
  658. finally:
  659. with cls._lock:
  660. if mode == "r":
  661. cls._readers -= 1
  662. else:
  663. cls._writer = False
  664. if cls._readers == 0:
  665. if os.name == "nt":
  666. handle = msvcrt.get_osfhandle(cls._lock_file.fileno())
  667. overlapped = Overlapped()
  668. if not unlock_file_ex(handle, 0, 1, 0, overlapped):
  669. cls.logger.debug("Unlocking not supported")
  670. elif os.name == "posix":
  671. try:
  672. fcntl.flock(cls._lock_file.fileno(), fcntl.LOCK_UN)
  673. except OSError:
  674. cls.logger.debug("Unlocking not supported")
  675. cls._lock_file_locked = False
  676. if cls._waiters:
  677. cls._waiters[0].notify()
  678. if (cls.configuration.getboolean("storage", "close_lock_file")
  679. and cls._readers == 0 and not cls._waiters):
  680. cls._lock_file.close()
  681. cls._lock_file = None