upload.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2014 Jean-Marc Martins
  3. # Copyright © 2012-2017 Guillaume Ayoub
  4. # Copyright © 2017-2022 Unrud <unrud@outlook.com>
  5. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import errno
  20. import os
  21. import pickle
  22. import sys
  23. from typing import Iterable, Iterator, TextIO, cast
  24. import radicale.item as radicale_item
  25. from radicale import pathutils
  26. from radicale.log import logger
  27. from radicale.storage.multifilesystem.base import CollectionBase
  28. from radicale.storage.multifilesystem.cache import CollectionPartCache
  29. from radicale.storage.multifilesystem.get import CollectionPartGet
  30. from radicale.storage.multifilesystem.history import CollectionPartHistory
  31. class CollectionPartUpload(CollectionPartGet, CollectionPartCache,
  32. CollectionPartHistory, CollectionBase):
  33. def upload(self, href: str, item: radicale_item.Item
  34. ) -> radicale_item.Item:
  35. if not pathutils.is_safe_filesystem_path_component(href):
  36. raise pathutils.UnsafePathError(href)
  37. path = pathutils.path_to_filesystem(self._filesystem_path, href)
  38. try:
  39. cache_hash = self._item_cache_hash(item.serialize().encode(self._encoding))
  40. logger.debug("Store cache for: %r with hash %r", path, cache_hash)
  41. self._store_item_cache(href, item, cache_hash)
  42. except Exception as e:
  43. raise ValueError("Failed to store item %r in collection %r: %s" %
  44. (href, self.path, e)) from e
  45. # TODO: better fix for "mypy"
  46. with self._atomic_write(path, newline="") as fo: # type: ignore
  47. f = cast(TextIO, fo)
  48. f.write(item.serialize())
  49. # Clean the cache after the actual item is stored, or the cache entry
  50. # will be removed again.
  51. self._clean_item_cache()
  52. # Track the change
  53. self._update_history_etag(href, item)
  54. self._clean_history()
  55. uploaded_item = self._get(href, verify_href=False)
  56. if uploaded_item is None:
  57. raise RuntimeError("Storage modified externally")
  58. return uploaded_item
  59. def _upload_all_nonatomic(self, items: Iterable[radicale_item.Item],
  60. suffix: str = "") -> None:
  61. """Upload a new set of items non-atomic"""
  62. def is_safe_free_href(href: str) -> bool:
  63. return (pathutils.is_safe_filesystem_path_component(href) and
  64. not os.path.lexists(
  65. os.path.join(self._filesystem_path, href)))
  66. def get_safe_free_hrefs(uid: str) -> Iterator[str]:
  67. for href in [uid if uid.lower().endswith(suffix.lower())
  68. else uid + suffix,
  69. radicale_item.get_etag(uid).strip('"') + suffix]:
  70. if is_safe_free_href(href):
  71. yield href
  72. yield radicale_item.find_available_uid(
  73. lambda href: not is_safe_free_href(href), suffix)
  74. cache_folder = self._storage._get_collection_cache_subfolder(self._filesystem_path, ".Radicale.cache", "item")
  75. self._storage._makedirs_synced(cache_folder)
  76. for item in items:
  77. uid = item.uid
  78. logger.debug("Store item from list with uid: '%s'" % uid)
  79. try:
  80. cache_content = self._item_cache_content(item)
  81. except Exception as e:
  82. raise ValueError(
  83. "Failed to store item %r in temporary collection %r: %s" %
  84. (uid, self.path, e)) from e
  85. for href in get_safe_free_hrefs(uid):
  86. try:
  87. f = open(os.path.join(self._filesystem_path, href),
  88. "w", newline="", encoding=self._encoding)
  89. except OSError as e:
  90. if (sys.platform != "win32" and e.errno == errno.EINVAL or
  91. sys.platform == "win32" and e.errno == 123):
  92. # not a valid filename
  93. continue
  94. raise
  95. break
  96. else:
  97. raise RuntimeError("No href found for item %r in temporary "
  98. "collection %r" % (uid, self.path))
  99. with f:
  100. f.write(item.serialize())
  101. f.flush()
  102. self._storage._fsync(f)
  103. with open(os.path.join(cache_folder, href), "wb") as fb:
  104. cache_hash = self._item_cache_hash(item.serialize().encode(self._encoding))
  105. logger.debug("Store cache for: %r with hash %r", fb.name, cache_hash)
  106. pickle.dump(cache_content, fb)
  107. fb.flush()
  108. self._storage._fsync(fb)
  109. self._storage._sync_directory(cache_folder)
  110. self._storage._sync_directory(self._filesystem_path)