upload.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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.storage.multifilesystem.base import CollectionBase
  27. from radicale.storage.multifilesystem.cache import CollectionPartCache
  28. from radicale.storage.multifilesystem.get import CollectionPartGet
  29. from radicale.storage.multifilesystem.history import CollectionPartHistory
  30. class CollectionPartUpload(CollectionPartGet, CollectionPartCache,
  31. CollectionPartHistory, CollectionBase):
  32. def upload(self, href: str, item: radicale_item.Item
  33. ) -> radicale_item.Item:
  34. if not pathutils.is_safe_filesystem_path_component(href):
  35. raise pathutils.UnsafePathError(href)
  36. try:
  37. self._store_item_cache(href, item)
  38. except Exception as e:
  39. raise ValueError("Failed to store item %r in collection %r: %s" %
  40. (href, self.path, e)) from e
  41. path = pathutils.path_to_filesystem(self._filesystem_path, href)
  42. # TODO: better fix for "mypy"
  43. with self._atomic_write(path, newline="") as fo: # type: ignore
  44. f = cast(TextIO, fo)
  45. f.write(item.serialize())
  46. # Clean the cache after the actual item is stored, or the cache entry
  47. # will be removed again.
  48. self._clean_item_cache()
  49. # Track the change
  50. self._update_history_etag(href, item)
  51. self._clean_history()
  52. uploaded_item = self._get(href, verify_href=False)
  53. if uploaded_item is None:
  54. raise RuntimeError("Storage modified externally")
  55. return uploaded_item
  56. def _upload_all_nonatomic(self, items: Iterable[radicale_item.Item],
  57. suffix: str = "") -> None:
  58. """Upload a new set of items non-atomic"""
  59. def is_safe_free_href(href: str) -> bool:
  60. return (pathutils.is_safe_filesystem_path_component(href) and
  61. not os.path.lexists(
  62. os.path.join(self._filesystem_path, href)))
  63. def get_safe_free_hrefs(uid: str) -> Iterator[str]:
  64. for href in [uid if uid.lower().endswith(suffix.lower())
  65. else uid + suffix,
  66. radicale_item.get_etag(uid).strip('"') + suffix]:
  67. if is_safe_free_href(href):
  68. yield href
  69. yield radicale_item.find_available_uid(
  70. lambda href: not is_safe_free_href(href), suffix)
  71. cache_folder = self._storage._get_collection_cache_folder(self._filesystem_path,
  72. ".Radicale.cache", "item")
  73. self._storage._makedirs_synced(cache_folder)
  74. for item in items:
  75. uid = item.uid
  76. try:
  77. cache_content = self._item_cache_content(item)
  78. except Exception as e:
  79. raise ValueError(
  80. "Failed to store item %r in temporary collection %r: %s" %
  81. (uid, self.path, e)) from e
  82. for href in get_safe_free_hrefs(uid):
  83. try:
  84. f = open(os.path.join(self._filesystem_path, href),
  85. "w", newline="", encoding=self._encoding)
  86. except OSError as e:
  87. if (sys.platform != "win32" and e.errno == errno.EINVAL or
  88. sys.platform == "win32" and e.errno == 123):
  89. # not a valid filename
  90. continue
  91. raise
  92. break
  93. else:
  94. raise RuntimeError("No href found for item %r in temporary "
  95. "collection %r" % (uid, self.path))
  96. with f:
  97. f.write(item.serialize())
  98. f.flush()
  99. self._storage._fsync(f)
  100. with open(os.path.join(cache_folder, href), "wb") as fb:
  101. pickle.dump(cache_content, fb)
  102. fb.flush()
  103. self._storage._fsync(fb)
  104. self._storage._sync_directory(cache_folder)
  105. self._storage._sync_directory(self._filesystem_path)