storage.py 28 KB

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