storage.py 29 KB

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