You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

233 lines
8.0 KiB

  1. import importlib.util
  2. import os
  3. import stat
  4. import typing
  5. from email.utils import parsedate
  6. import anyio
  7. from starlette.datastructures import URL, Headers
  8. from starlette.exceptions import HTTPException
  9. from starlette.responses import FileResponse, RedirectResponse, Response
  10. from starlette.types import Receive, Scope, Send
  11. PathLike = typing.Union[str, "os.PathLike[str]"]
  12. class NotModifiedResponse(Response):
  13. NOT_MODIFIED_HEADERS = (
  14. "cache-control",
  15. "content-location",
  16. "date",
  17. "etag",
  18. "expires",
  19. "vary",
  20. )
  21. def __init__(self, headers: Headers):
  22. super().__init__(
  23. status_code=304,
  24. headers={
  25. name: value
  26. for name, value in headers.items()
  27. if name in self.NOT_MODIFIED_HEADERS
  28. },
  29. )
  30. class StaticFiles:
  31. def __init__(
  32. self,
  33. *,
  34. directory: PathLike = None,
  35. packages: typing.List[str] = None,
  36. html: bool = False,
  37. check_dir: bool = True,
  38. ) -> None:
  39. self.directory = directory
  40. self.packages = packages
  41. self.all_directories = self.get_directories(directory, packages)
  42. self.html = html
  43. self.config_checked = False
  44. if check_dir and directory is not None and not os.path.isdir(directory):
  45. raise RuntimeError(f"Directory '{directory}' does not exist")
  46. def get_directories(
  47. self, directory: PathLike = None, packages: typing.List[str] = None
  48. ) -> typing.List[PathLike]:
  49. """
  50. Given `directory` and `packages` arguments, return a list of all the
  51. directories that should be used for serving static files from.
  52. """
  53. directories = []
  54. if directory is not None:
  55. directories.append(directory)
  56. for package in packages or []:
  57. spec = importlib.util.find_spec(package)
  58. assert spec is not None, f"Package {package!r} could not be found."
  59. assert (
  60. spec.origin is not None
  61. ), f"Directory 'statics' in package {package!r} could not be found."
  62. package_directory = os.path.normpath(
  63. os.path.join(spec.origin, "..", "statics")
  64. )
  65. assert os.path.isdir(
  66. package_directory
  67. ), f"Directory 'statics' in package {package!r} could not be found."
  68. directories.append(package_directory)
  69. return directories
  70. async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
  71. """
  72. The ASGI entry point.
  73. """
  74. assert scope["type"] == "http"
  75. if not self.config_checked:
  76. await self.check_config()
  77. self.config_checked = True
  78. path = self.get_path(scope)
  79. response = await self.get_response(path, scope)
  80. await response(scope, receive, send)
  81. def get_path(self, scope: Scope) -> str:
  82. """
  83. Given the ASGI scope, return the `path` string to serve up,
  84. with OS specific path seperators, and any '..', '.' components removed.
  85. """
  86. return os.path.normpath(os.path.join(*scope["path"].split("/")))
  87. async def get_response(self, path: str, scope: Scope) -> Response:
  88. """
  89. Returns an HTTP response, given the incoming path, method and request headers.
  90. """
  91. if scope["method"] not in ("GET", "HEAD"):
  92. raise HTTPException(status_code=405)
  93. try:
  94. full_path, stat_result = await anyio.to_thread.run_sync(
  95. self.lookup_path, path
  96. )
  97. except PermissionError:
  98. raise HTTPException(status_code=401)
  99. except OSError:
  100. raise
  101. if stat_result and stat.S_ISREG(stat_result.st_mode):
  102. # We have a static file to serve.
  103. return self.file_response(full_path, stat_result, scope)
  104. elif stat_result and stat.S_ISDIR(stat_result.st_mode) and self.html:
  105. # We're in HTML mode, and have got a directory URL.
  106. # Check if we have 'index.html' file to serve.
  107. index_path = os.path.join(path, "index.html")
  108. full_path, stat_result = await anyio.to_thread.run_sync(
  109. self.lookup_path, index_path
  110. )
  111. if stat_result is not None and stat.S_ISREG(stat_result.st_mode):
  112. if not scope["path"].endswith("/"):
  113. # Directory URLs should redirect to always end in "/".
  114. url = URL(scope=scope)
  115. url = url.replace(path=url.path + "/")
  116. return RedirectResponse(url=url)
  117. return self.file_response(full_path, stat_result, scope)
  118. if self.html:
  119. # Check for '404.html' if we're in HTML mode.
  120. full_path, stat_result = await anyio.to_thread.run_sync(
  121. self.lookup_path, "404.html"
  122. )
  123. if stat_result and stat.S_ISREG(stat_result.st_mode):
  124. return FileResponse(
  125. full_path,
  126. stat_result=stat_result,
  127. method=scope["method"],
  128. status_code=404,
  129. )
  130. raise HTTPException(status_code=404)
  131. def lookup_path(
  132. self, path: str
  133. ) -> typing.Tuple[str, typing.Optional[os.stat_result]]:
  134. for directory in self.all_directories:
  135. full_path = os.path.realpath(os.path.join(directory, path))
  136. directory = os.path.realpath(directory)
  137. if os.path.commonprefix([full_path, directory]) != directory:
  138. # Don't allow misbehaving clients to break out of the static files
  139. # directory.
  140. continue
  141. try:
  142. return full_path, os.stat(full_path)
  143. except (FileNotFoundError, NotADirectoryError):
  144. continue
  145. return "", None
  146. def file_response(
  147. self,
  148. full_path: PathLike,
  149. stat_result: os.stat_result,
  150. scope: Scope,
  151. status_code: int = 200,
  152. ) -> Response:
  153. method = scope["method"]
  154. request_headers = Headers(scope=scope)
  155. response = FileResponse(
  156. full_path, status_code=status_code, stat_result=stat_result, method=method
  157. )
  158. if self.is_not_modified(response.headers, request_headers):
  159. return NotModifiedResponse(response.headers)
  160. return response
  161. async def check_config(self) -> None:
  162. """
  163. Perform a one-off configuration check that StaticFiles is actually
  164. pointed at a directory, so that we can raise loud errors rather than
  165. just returning 404 responses.
  166. """
  167. if self.directory is None:
  168. return
  169. try:
  170. stat_result = await anyio.to_thread.run_sync(os.stat, self.directory)
  171. except FileNotFoundError:
  172. raise RuntimeError(
  173. f"StaticFiles directory '{self.directory}' does not exist."
  174. )
  175. if not (stat.S_ISDIR(stat_result.st_mode) or stat.S_ISLNK(stat_result.st_mode)):
  176. raise RuntimeError(
  177. f"StaticFiles path '{self.directory}' is not a directory."
  178. )
  179. def is_not_modified(
  180. self, response_headers: Headers, request_headers: Headers
  181. ) -> bool:
  182. """
  183. Given the request and response headers, return `True` if an HTTP
  184. "Not Modified" response could be returned instead.
  185. """
  186. try:
  187. if_none_match = request_headers["if-none-match"]
  188. etag = response_headers["etag"]
  189. if if_none_match == etag:
  190. return True
  191. except KeyError:
  192. pass
  193. try:
  194. if_modified_since = parsedate(request_headers["if-modified-since"])
  195. last_modified = parsedate(response_headers["last-modified"])
  196. if (
  197. if_modified_since is not None
  198. and last_modified is not None
  199. and if_modified_since >= last_modified
  200. ):
  201. return True
  202. except KeyError:
  203. pass
  204. return False