httputils.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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 time
  25. from http import client
  26. from typing import List, Mapping, cast
  27. from radicale import config, pathutils, types
  28. from radicale.log import logger
  29. NOT_ALLOWED: types.WSGIResponse = (
  30. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  31. "Access to the requested resource forbidden.")
  32. FORBIDDEN: types.WSGIResponse = (
  33. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  34. "Action on the requested resource refused.")
  35. BAD_REQUEST: types.WSGIResponse = (
  36. client.BAD_REQUEST, (("Content-Type", "text/plain"),), "Bad Request")
  37. NOT_FOUND: types.WSGIResponse = (
  38. client.NOT_FOUND, (("Content-Type", "text/plain"),),
  39. "The requested resource could not be found.")
  40. CONFLICT: types.WSGIResponse = (
  41. client.CONFLICT, (("Content-Type", "text/plain"),),
  42. "Conflict in the request.")
  43. METHOD_NOT_ALLOWED: types.WSGIResponse = (
  44. client.METHOD_NOT_ALLOWED, (("Content-Type", "text/plain"),),
  45. "The method is not allowed on the requested resource.")
  46. PRECONDITION_FAILED: types.WSGIResponse = (
  47. client.PRECONDITION_FAILED,
  48. (("Content-Type", "text/plain"),), "Precondition failed.")
  49. REQUEST_TIMEOUT: types.WSGIResponse = (
  50. client.REQUEST_TIMEOUT, (("Content-Type", "text/plain"),),
  51. "Connection timed out.")
  52. REQUEST_ENTITY_TOO_LARGE: types.WSGIResponse = (
  53. client.REQUEST_ENTITY_TOO_LARGE, (("Content-Type", "text/plain"),),
  54. "Request body too large.")
  55. REMOTE_DESTINATION: types.WSGIResponse = (
  56. client.BAD_GATEWAY, (("Content-Type", "text/plain"),),
  57. "Remote destination not supported.")
  58. DIRECTORY_LISTING: types.WSGIResponse = (
  59. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  60. "Directory listings are not supported.")
  61. INTERNAL_SERVER_ERROR: types.WSGIResponse = (
  62. client.INTERNAL_SERVER_ERROR, (("Content-Type", "text/plain"),),
  63. "A server error occurred. Please contact the administrator.")
  64. DAV_HEADERS: str = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  65. MIMETYPES: Mapping[str, str] = {
  66. ".css": "text/css",
  67. ".eot": "application/vnd.ms-fontobject",
  68. ".gif": "image/gif",
  69. ".html": "text/html",
  70. ".js": "application/javascript",
  71. ".manifest": "text/cache-manifest",
  72. ".png": "image/png",
  73. ".svg": "image/svg+xml",
  74. ".ttf": "application/font-sfnt",
  75. ".txt": "text/plain",
  76. ".woff": "application/font-woff",
  77. ".woff2": "font/woff2",
  78. ".xml": "text/xml"}
  79. FALLBACK_MIMETYPE: str = "application/octet-stream"
  80. def decode_request(configuration: "config.Configuration",
  81. environ: types.WSGIEnviron, text: bytes) -> str:
  82. """Try to magically decode ``text`` according to given ``environ``."""
  83. # List of charsets to try
  84. charsets: List[str] = []
  85. # First append content charset given in the request
  86. content_type = environ.get("CONTENT_TYPE")
  87. if content_type and "charset=" in content_type:
  88. charsets.append(
  89. content_type.split("charset=")[1].split(";")[0].strip())
  90. # Then append default Radicale charset
  91. charsets.append(cast(str, configuration.get("encoding", "request")))
  92. # Then append various fallbacks
  93. charsets.append("utf-8")
  94. charsets.append("iso8859-1")
  95. # Remove duplicates
  96. for i, s in reversed(list(enumerate(charsets))):
  97. if s in charsets[:i]:
  98. del charsets[i]
  99. # Try to decode
  100. for charset in charsets:
  101. with contextlib.suppress(UnicodeDecodeError):
  102. return text.decode(charset)
  103. raise UnicodeDecodeError("decode_request", text, 0, len(text),
  104. "all codecs failed [%s]" % ", ".join(charsets))
  105. def read_raw_request_body(configuration: "config.Configuration",
  106. environ: types.WSGIEnviron) -> bytes:
  107. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  108. if not content_length:
  109. return b""
  110. content = environ["wsgi.input"].read(content_length)
  111. if len(content) < content_length:
  112. raise RuntimeError("Request body too short: %d" % len(content))
  113. return content
  114. def read_request_body(configuration: "config.Configuration",
  115. environ: types.WSGIEnviron) -> str:
  116. content = decode_request(configuration, environ,
  117. read_raw_request_body(configuration, environ))
  118. logger.debug("Request content:\n%s", content)
  119. return content
  120. def redirect(location: str, status: int = client.FOUND) -> types.WSGIResponse:
  121. return (status,
  122. {"Location": location, "Content-Type": "text/plain"},
  123. "Redirected to %s" % location)
  124. def serve_folder(folder: str, base_prefix: str, path: str,
  125. path_prefix: str = "/.web", index_file: str = "index.html",
  126. mimetypes: Mapping[str, str] = MIMETYPES,
  127. fallback_mimetype: str = FALLBACK_MIMETYPE,
  128. ) -> types.WSGIResponse:
  129. if path != path_prefix and not path.startswith(path_prefix):
  130. raise ValueError("path must start with path_prefix: %r --> %r" %
  131. (path_prefix, path))
  132. assert pathutils.sanitize_path(path) == path
  133. try:
  134. filesystem_path = pathutils.path_to_filesystem(
  135. folder, path[len(path_prefix):].strip("/"))
  136. except ValueError as e:
  137. logger.debug("Web content with unsafe path %r requested: %s",
  138. path, e, exc_info=True)
  139. return NOT_FOUND
  140. if os.path.isdir(filesystem_path) and not path.endswith("/"):
  141. return redirect(base_prefix + path + "/")
  142. if os.path.isdir(filesystem_path) and index_file:
  143. filesystem_path = os.path.join(filesystem_path, index_file)
  144. if not os.path.isfile(filesystem_path):
  145. return NOT_FOUND
  146. content_type = MIMETYPES.get(
  147. os.path.splitext(filesystem_path)[1].lower(), FALLBACK_MIMETYPE)
  148. with open(filesystem_path, "rb") as f:
  149. answer = f.read()
  150. last_modified = time.strftime(
  151. "%a, %d %b %Y %H:%M:%S GMT",
  152. time.gmtime(os.fstat(f.fileno()).st_mtime))
  153. headers = {
  154. "Content-Type": content_type,
  155. "Last-Modified": last_modified}
  156. return client.OK, headers, answer