storage.py 28 KB

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