httputils.py 8.3 KB

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