httputils.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2022 Unrud <unrud@outlook.com>
  6. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Helper functions for HTTP.
  22. """
  23. import contextlib
  24. import os
  25. import pathlib
  26. import sys
  27. import time
  28. from http import client
  29. from typing import List, Mapping, Union, cast
  30. from radicale import config, pathutils, types
  31. from radicale.log import logger
  32. if sys.version_info < (3, 9):
  33. import pkg_resources
  34. _TRAVERSABLE_LIKE_TYPE = pathlib.Path
  35. else:
  36. import importlib.abc
  37. from importlib import resources
  38. _TRAVERSABLE_LIKE_TYPE = Union[importlib.abc.Traversable, pathlib.Path]
  39. NOT_ALLOWED: types.WSGIResponse = (
  40. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  41. "Access to the requested resource forbidden.")
  42. FORBIDDEN: types.WSGIResponse = (
  43. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  44. "Action on the requested resource refused.")
  45. BAD_REQUEST: types.WSGIResponse = (
  46. client.BAD_REQUEST, (("Content-Type", "text/plain"),), "Bad Request")
  47. NOT_FOUND: types.WSGIResponse = (
  48. client.NOT_FOUND, (("Content-Type", "text/plain"),),
  49. "The requested resource could not be found.")
  50. CONFLICT: types.WSGIResponse = (
  51. client.CONFLICT, (("Content-Type", "text/plain"),),
  52. "Conflict in the request.")
  53. METHOD_NOT_ALLOWED: types.WSGIResponse = (
  54. client.METHOD_NOT_ALLOWED, (("Content-Type", "text/plain"),),
  55. "The method is not allowed on the requested resource.")
  56. PRECONDITION_FAILED: types.WSGIResponse = (
  57. client.PRECONDITION_FAILED,
  58. (("Content-Type", "text/plain"),), "Precondition failed.")
  59. REQUEST_TIMEOUT: types.WSGIResponse = (
  60. client.REQUEST_TIMEOUT, (("Content-Type", "text/plain"),),
  61. "Connection timed out.")
  62. REQUEST_ENTITY_TOO_LARGE: types.WSGIResponse = (
  63. client.REQUEST_ENTITY_TOO_LARGE, (("Content-Type", "text/plain"),),
  64. "Request body too large.")
  65. REMOTE_DESTINATION: types.WSGIResponse = (
  66. client.BAD_GATEWAY, (("Content-Type", "text/plain"),),
  67. "Remote destination not supported.")
  68. DIRECTORY_LISTING: types.WSGIResponse = (
  69. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  70. "Directory listings are not supported.")
  71. INTERNAL_SERVER_ERROR: types.WSGIResponse = (
  72. client.INTERNAL_SERVER_ERROR, (("Content-Type", "text/plain"),),
  73. "A server error occurred. Please contact the administrator.")
  74. DAV_HEADERS: str = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  75. MIMETYPES: Mapping[str, str] = {
  76. ".css": "text/css",
  77. ".eot": "application/vnd.ms-fontobject",
  78. ".gif": "image/gif",
  79. ".html": "text/html",
  80. ".js": "application/javascript",
  81. ".manifest": "text/cache-manifest",
  82. ".png": "image/png",
  83. ".svg": "image/svg+xml",
  84. ".ttf": "application/font-sfnt",
  85. ".txt": "text/plain",
  86. ".woff": "application/font-woff",
  87. ".woff2": "font/woff2",
  88. ".xml": "text/xml"}
  89. FALLBACK_MIMETYPE: str = "application/octet-stream"
  90. def decode_request(configuration: "config.Configuration",
  91. environ: types.WSGIEnviron, text: bytes) -> str:
  92. """Try to magically decode ``text`` according to given ``environ``."""
  93. # List of charsets to try
  94. charsets: List[str] = []
  95. # First append content charset given in the request
  96. content_type = environ.get("CONTENT_TYPE")
  97. if content_type and "charset=" in content_type:
  98. charsets.append(
  99. content_type.split("charset=")[1].split(";")[0].strip())
  100. # Then append default Radicale charset
  101. charsets.append(cast(str, configuration.get("encoding", "request")))
  102. # Then append various fallbacks
  103. charsets.append("utf-8")
  104. charsets.append("iso8859-1")
  105. # Remove duplicates
  106. for i, s in reversed(list(enumerate(charsets))):
  107. if s in charsets[:i]:
  108. del charsets[i]
  109. # Try to decode
  110. for charset in charsets:
  111. with contextlib.suppress(UnicodeDecodeError):
  112. return text.decode(charset)
  113. raise UnicodeDecodeError("decode_request", text, 0, len(text),
  114. "all codecs failed [%s]" % ", ".join(charsets))
  115. def read_raw_request_body(configuration: "config.Configuration",
  116. environ: types.WSGIEnviron) -> bytes:
  117. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  118. if not content_length:
  119. return b""
  120. content = environ["wsgi.input"].read(content_length)
  121. if len(content) < content_length:
  122. raise RuntimeError("Request body too short: %d" % len(content))
  123. return content
  124. def read_request_body(configuration: "config.Configuration",
  125. environ: types.WSGIEnviron) -> str:
  126. content = decode_request(configuration, environ,
  127. read_raw_request_body(configuration, environ))
  128. if configuration.get("logging", "request_content_on_debug"):
  129. logger.debug("Request content:\n%s", content)
  130. else:
  131. logger.debug("Request content: suppressed by config/option [logging] request_content_on_debug")
  132. return content
  133. def redirect(location: str, status: int = client.FOUND) -> types.WSGIResponse:
  134. return (status,
  135. {"Location": location, "Content-Type": "text/plain"},
  136. "Redirected to %s" % location)
  137. def _serve_traversable(
  138. traversable: _TRAVERSABLE_LIKE_TYPE, base_prefix: str, path: str,
  139. path_prefix: str, index_file: str, mimetypes: Mapping[str, str],
  140. fallback_mimetype: str) -> types.WSGIResponse:
  141. if path != path_prefix and not path.startswith(path_prefix):
  142. raise ValueError("path must start with path_prefix: %r --> %r" %
  143. (path_prefix, path))
  144. assert pathutils.sanitize_path(path) == path
  145. parts_path = path[len(path_prefix):].strip('/')
  146. parts = parts_path.split("/") if parts_path else []
  147. for part in parts:
  148. if not pathutils.is_safe_filesystem_path_component(part):
  149. logger.debug("Web content with unsafe path %r requested", path)
  150. return NOT_FOUND
  151. if (not traversable.is_dir() or
  152. all(part != entry.name for entry in traversable.iterdir())):
  153. return NOT_FOUND
  154. traversable = traversable.joinpath(part)
  155. if traversable.is_dir():
  156. if not path.endswith("/"):
  157. return redirect(base_prefix + path + "/")
  158. if not index_file:
  159. return NOT_FOUND
  160. traversable = traversable.joinpath(index_file)
  161. if not traversable.is_file():
  162. return NOT_FOUND
  163. content_type = MIMETYPES.get(
  164. os.path.splitext(traversable.name)[1].lower(), FALLBACK_MIMETYPE)
  165. headers = {"Content-Type": content_type}
  166. if isinstance(traversable, pathlib.Path):
  167. headers["Last-Modified"] = time.strftime(
  168. "%a, %d %b %Y %H:%M:%S GMT",
  169. time.gmtime(traversable.stat().st_mtime))
  170. answer = traversable.read_bytes()
  171. return client.OK, headers, answer
  172. def serve_resource(
  173. package: str, resource: str, base_prefix: str, path: str,
  174. path_prefix: str = "/.web", index_file: str = "index.html",
  175. mimetypes: Mapping[str, str] = MIMETYPES,
  176. fallback_mimetype: str = FALLBACK_MIMETYPE) -> types.WSGIResponse:
  177. if sys.version_info < (3, 9):
  178. traversable = pathlib.Path(
  179. pkg_resources.resource_filename(package, resource))
  180. else:
  181. traversable = resources.files(package).joinpath(resource)
  182. return _serve_traversable(traversable, base_prefix, path, path_prefix,
  183. index_file, mimetypes, fallback_mimetype)
  184. def serve_folder(
  185. folder: str, base_prefix: str, path: str,
  186. path_prefix: str = "/.web", index_file: str = "index.html",
  187. mimetypes: Mapping[str, str] = MIMETYPES,
  188. fallback_mimetype: str = FALLBACK_MIMETYPE) -> types.WSGIResponse:
  189. # deprecated: use `serve_resource` instead
  190. traversable = pathlib.Path(folder)
  191. return _serve_traversable(traversable, base_prefix, path, path_prefix,
  192. index_file, mimetypes, fallback_mimetype)