httputils.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. from http import client
  24. from typing import List, cast
  25. from radicale import config, types
  26. from radicale.log import logger
  27. NOT_ALLOWED: types.WSGIResponse = (
  28. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  29. "Access to the requested resource forbidden.")
  30. FORBIDDEN: types.WSGIResponse = (
  31. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  32. "Action on the requested resource refused.")
  33. BAD_REQUEST: types.WSGIResponse = (
  34. client.BAD_REQUEST, (("Content-Type", "text/plain"),), "Bad Request")
  35. NOT_FOUND: types.WSGIResponse = (
  36. client.NOT_FOUND, (("Content-Type", "text/plain"),),
  37. "The requested resource could not be found.")
  38. CONFLICT: types.WSGIResponse = (
  39. client.CONFLICT, (("Content-Type", "text/plain"),),
  40. "Conflict in the request.")
  41. METHOD_NOT_ALLOWED: types.WSGIResponse = (
  42. client.METHOD_NOT_ALLOWED, (("Content-Type", "text/plain"),),
  43. "The method is not allowed on the requested resource.")
  44. PRECONDITION_FAILED: types.WSGIResponse = (
  45. client.PRECONDITION_FAILED,
  46. (("Content-Type", "text/plain"),), "Precondition failed.")
  47. REQUEST_TIMEOUT: types.WSGIResponse = (
  48. client.REQUEST_TIMEOUT, (("Content-Type", "text/plain"),),
  49. "Connection timed out.")
  50. REQUEST_ENTITY_TOO_LARGE: types.WSGIResponse = (
  51. client.REQUEST_ENTITY_TOO_LARGE, (("Content-Type", "text/plain"),),
  52. "Request body too large.")
  53. REMOTE_DESTINATION: types.WSGIResponse = (
  54. client.BAD_GATEWAY, (("Content-Type", "text/plain"),),
  55. "Remote destination not supported.")
  56. DIRECTORY_LISTING: types.WSGIResponse = (
  57. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  58. "Directory listings are not supported.")
  59. INTERNAL_SERVER_ERROR: types.WSGIResponse = (
  60. client.INTERNAL_SERVER_ERROR, (("Content-Type", "text/plain"),),
  61. "A server error occurred. Please contact the administrator.")
  62. DAV_HEADERS: str = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  63. def decode_request(configuration: "config.Configuration",
  64. environ: types.WSGIEnviron, text: bytes) -> str:
  65. """Try to magically decode ``text`` according to given ``environ``."""
  66. # List of charsets to try
  67. charsets: List[str] = []
  68. # First append content charset given in the request
  69. content_type = environ.get("CONTENT_TYPE")
  70. if content_type and "charset=" in content_type:
  71. charsets.append(
  72. content_type.split("charset=")[1].split(";")[0].strip())
  73. # Then append default Radicale charset
  74. charsets.append(cast(str, configuration.get("encoding", "request")))
  75. # Then append various fallbacks
  76. charsets.append("utf-8")
  77. charsets.append("iso8859-1")
  78. # Remove duplicates
  79. for i, s in reversed(list(enumerate(charsets))):
  80. if s in charsets[:i]:
  81. del charsets[i]
  82. # Try to decode
  83. for charset in charsets:
  84. with contextlib.suppress(UnicodeDecodeError):
  85. return text.decode(charset)
  86. raise UnicodeDecodeError("decode_request", text, 0, len(text),
  87. "all codecs failed [%s]" % ", ".join(charsets))
  88. def read_raw_request_body(configuration: "config.Configuration",
  89. environ: types.WSGIEnviron) -> bytes:
  90. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  91. if not content_length:
  92. return b""
  93. content = environ["wsgi.input"].read(content_length)
  94. if len(content) < content_length:
  95. raise RuntimeError("Request body too short: %d" % len(content))
  96. return content
  97. def read_request_body(configuration: "config.Configuration",
  98. environ: types.WSGIEnviron) -> str:
  99. content = decode_request(configuration, environ,
  100. read_raw_request_body(configuration, environ))
  101. logger.debug("Request content:\n%s", content)
  102. return content