| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import errno |
| 4 |
import os |
| 5 |
import re |
| 6 |
import stat |
| 7 |
from email.utils import formatdate |
| 8 |
from email.utils import parsedate |
| 9 |
from http import HTTPStatus |
| 10 |
from io import BufferedIOBase |
| 11 |
from time import mktime |
| 12 |
from urllib.parse import quote |
| 13 |
from wsgiref.headers import Headers |
| 14 |
|
| 15 |
|
| 16 |
class Response: |
| 17 |
__slots__ = ("status", "headers", "file") |
| 18 |
|
| 19 |
def __init__(self, status, headers, file): |
| 20 |
self.status = status |
| 21 |
self.headers = headers |
| 22 |
self.file = file |
| 23 |
|
| 24 |
|
| 25 |
NOT_ALLOWED_RESPONSE = Response( |
| 26 |
status=HTTPStatus.METHOD_NOT_ALLOWED, |
| 27 |
headers=[("Allow", "GET, HEAD")], |
| 28 |
file=None, |
| 29 |
) |
| 30 |
|
| 31 |
# Headers which should be returned with a 304 Not Modified response as |
| 32 |
# specified here: https://tools.ietf.org/html/rfc7232#section-4.1 |
| 33 |
NOT_MODIFIED_HEADERS = ( |
| 34 |
"Cache-Control", |
| 35 |
"Content-Location", |
| 36 |
"Date", |
| 37 |
"ETag", |
| 38 |
"Expires", |
| 39 |
"Vary", |
| 40 |
) |
| 41 |
|
| 42 |
|
| 43 |
class SlicedFile(BufferedIOBase): |
| 44 |
""" |
| 45 |
A file like wrapper to handle seeking to the start byte of a range request |
| 46 |
and to return no further output once the end byte of a range request has |
| 47 |
been reached. |
| 48 |
""" |
| 49 |
|
| 50 |
def __init__(self, fileobj, start, end): |
| 51 |
fileobj.seek(start) |
| 52 |
self.fileobj = fileobj |
| 53 |
self.remaining = end - start + 1 |
| 54 |
|
| 55 |
def read(self, size=-1): |
| 56 |
if self.remaining <= 0: |
| 57 |
return b"" |
| 58 |
if size < 0: |
| 59 |
size = self.remaining |
| 60 |
else: |
| 61 |
size = min(size, self.remaining) |
| 62 |
data = self.fileobj.read(size) |
| 63 |
self.remaining -= len(data) |
| 64 |
return data |
| 65 |
|
| 66 |
def close(self): |
| 67 |
super().close() |
| 68 |
self.fileobj.close() |
| 69 |
|
| 70 |
|
| 71 |
class StaticFile: |
| 72 |
def __init__(self, path, headers, encodings=None, stat_cache=None): |
| 73 |
files = self.get_file_stats(path, encodings, stat_cache) |
| 74 |
headers = self.get_headers(headers, files) |
| 75 |
self.last_modified = parsedate(headers["Last-Modified"]) |
| 76 |
self.etag = headers["ETag"] |
| 77 |
self.not_modified_response = self.get_not_modified_response(headers) |
| 78 |
self.alternatives = self.get_alternatives(headers, files) |
| 79 |
|
| 80 |
def get_response(self, method, request_headers): |
| 81 |
if method not in ("GET", "HEAD"): |
| 82 |
return NOT_ALLOWED_RESPONSE |
| 83 |
if self.is_not_modified(request_headers): |
| 84 |
return self.not_modified_response |
| 85 |
path, headers = self.get_path_and_headers(request_headers) |
| 86 |
if method != "HEAD": |
| 87 |
file_handle = open(path, "rb") |
| 88 |
else: |
| 89 |
file_handle = None |
| 90 |
range_header = request_headers.get("HTTP_RANGE") |
| 91 |
if range_header: |
| 92 |
try: |
| 93 |
return self.get_range_response(range_header, headers, file_handle) |
| 94 |
except ValueError: |
| 95 |
# If we can't interpret the Range request for any reason then |
| 96 |
# just ignore it and return the standard response (this |
| 97 |
# behaviour is allowed by the spec) |
| 98 |
pass |
| 99 |
return Response(HTTPStatus.OK, headers, file_handle) |
| 100 |
|
| 101 |
def get_range_response(self, range_header, base_headers, file_handle): |
| 102 |
headers = [] |
| 103 |
for item in base_headers: |
| 104 |
if item[0] == "Content-Length": |
| 105 |
size = int(item[1]) |
| 106 |
else: |
| 107 |
headers.append(item) |
| 108 |
start, end = self.get_byte_range(range_header, size) |
| 109 |
if start >= end: |
| 110 |
return self.get_range_not_satisfiable_response(file_handle, size) |
| 111 |
if file_handle is not None: |
| 112 |
file_handle = SlicedFile(file_handle, start, end) |
| 113 |
headers.append(("Content-Range", f"bytes {start}-{end}/{size}")) |
| 114 |
headers.append(("Content-Length", str(end - start + 1))) |
| 115 |
return Response(HTTPStatus.PARTIAL_CONTENT, headers, file_handle) |
| 116 |
|
| 117 |
def get_byte_range(self, range_header, size): |
| 118 |
start, end = self.parse_byte_range(range_header) |
| 119 |
if start < 0: |
| 120 |
start = max(start + size, 0) |
| 121 |
if end is None: |
| 122 |
end = size - 1 |
| 123 |
else: |
| 124 |
end = min(end, size - 1) |
| 125 |
return start, end |
| 126 |
|
| 127 |
@staticmethod |
| 128 |
def parse_byte_range(range_header): |
| 129 |
units, _, range_spec = range_header.strip().partition("=") |
| 130 |
if units != "bytes": |
| 131 |
raise ValueError() |
| 132 |
# Only handle a single range spec. Multiple ranges will trigger a |
| 133 |
# ValueError below which will result in the Range header being ignored |
| 134 |
start_str, sep, end_str = range_spec.strip().partition("-") |
| 135 |
if not sep: |
| 136 |
raise ValueError() |
| 137 |
if not start_str: |
| 138 |
start = -int(end_str) |
| 139 |
end = None |
| 140 |
else: |
| 141 |
start = int(start_str) |
| 142 |
end = int(end_str) if end_str else None |
| 143 |
return start, end |
| 144 |
|
| 145 |
@staticmethod |
| 146 |
def get_range_not_satisfiable_response(file_handle, size): |
| 147 |
if file_handle is not None: |
| 148 |
file_handle.close() |
| 149 |
return Response( |
| 150 |
HTTPStatus.REQUESTED_RANGE_NOT_SATISFIABLE, |
| 151 |
[("Content-Range", f"bytes */{size}")], |
| 152 |
None, |
| 153 |
) |
| 154 |
|
| 155 |
@staticmethod |
| 156 |
def get_file_stats(path, encodings, stat_cache): |
| 157 |
# Primary file has an encoding of None |
| 158 |
files = {None: FileEntry(path, stat_cache)} |
| 159 |
if encodings: |
| 160 |
for encoding, alt_path in encodings.items(): |
| 161 |
try: |
| 162 |
files[encoding] = FileEntry(alt_path, stat_cache) |
| 163 |
except MissingFileError: |
| 164 |
continue |
| 165 |
return files |
| 166 |
|
| 167 |
def get_headers(self, headers_list, files): |
| 168 |
headers = Headers(headers_list) |
| 169 |
main_file = files[None] |
| 170 |
if len(files) > 1: |
| 171 |
headers["Vary"] = "Accept-Encoding" |
| 172 |
if "Last-Modified" not in headers: |
| 173 |
mtime = main_file.mtime |
| 174 |
# Not all filesystems report mtimes, and sometimes they report an |
| 175 |
# mtime of 0 which we know is incorrect |
| 176 |
if mtime: |
| 177 |
headers["Last-Modified"] = formatdate(mtime, usegmt=True) |
| 178 |
if "ETag" not in headers: |
| 179 |
last_modified = parsedate(headers["Last-Modified"]) |
| 180 |
if last_modified: |
| 181 |
timestamp = int(mktime(last_modified)) |
| 182 |
headers["ETag"] = f'"{timestamp:x}-{main_file.size:x}"' |
| 183 |
return headers |
| 184 |
|
| 185 |
@staticmethod |
| 186 |
def get_not_modified_response(headers): |
| 187 |
not_modified_headers = [] |
| 188 |
for key in NOT_MODIFIED_HEADERS: |
| 189 |
if key in headers: |
| 190 |
not_modified_headers.append((key, headers[key])) |
| 191 |
return Response( |
| 192 |
status=HTTPStatus.NOT_MODIFIED, headers=not_modified_headers, file=None |
| 193 |
) |
| 194 |
|
| 195 |
@staticmethod |
| 196 |
def get_alternatives(base_headers, files): |
| 197 |
# Sort by size so that the smallest compressed alternative matches first |
| 198 |
alternatives = [] |
| 199 |
files_by_size = sorted(files.items(), key=lambda i: i[1].size) |
| 200 |
for encoding, file_entry in files_by_size: |
| 201 |
headers = Headers(base_headers.items()) |
| 202 |
headers["Content-Length"] = str(file_entry.size) |
| 203 |
if encoding: |
| 204 |
headers["Content-Encoding"] = encoding |
| 205 |
encoding_re = re.compile(r"\b%s\b" % encoding) |
| 206 |
else: |
| 207 |
encoding_re = re.compile("") |
| 208 |
alternatives.append((encoding_re, file_entry.path, headers.items())) |
| 209 |
return alternatives |
| 210 |
|
| 211 |
def is_not_modified(self, request_headers): |
| 212 |
previous_etag = request_headers.get("HTTP_IF_NONE_MATCH") |
| 213 |
if previous_etag is not None: |
| 214 |
return previous_etag == self.etag |
| 215 |
if self.last_modified is None: |
| 216 |
return False |
| 217 |
try: |
| 218 |
last_requested = request_headers["HTTP_IF_MODIFIED_SINCE"] |
| 219 |
except KeyError: |
| 220 |
return False |
| 221 |
last_requested_ts = parsedate(last_requested) |
| 222 |
if last_requested_ts is not None: |
| 223 |
return last_requested_ts >= self.last_modified |
| 224 |
return False |
| 225 |
|
| 226 |
def get_path_and_headers(self, request_headers): |
| 227 |
accept_encoding = request_headers.get("HTTP_ACCEPT_ENCODING", "") |
| 228 |
if accept_encoding == "*": |
| 229 |
accept_encoding = "" |
| 230 |
# These are sorted by size so first match is the best |
| 231 |
for encoding_re, path, headers in self.alternatives: |
| 232 |
if encoding_re.search(accept_encoding): |
| 233 |
return path, headers |
| 234 |
|
| 235 |
|
| 236 |
class Redirect: |
| 237 |
def __init__(self, location, headers=None): |
| 238 |
headers = list(headers.items()) if headers else [] |
| 239 |
headers.append(("Location", quote(location.encode("utf8")))) |
| 240 |
self.response = Response(HTTPStatus.FOUND, headers, None) |
| 241 |
|
| 242 |
def get_response(self, method, request_headers): |
| 243 |
return self.response |
| 244 |
|
| 245 |
|
| 246 |
class NotARegularFileError(Exception): |
| 247 |
pass |
| 248 |
|
| 249 |
|
| 250 |
class MissingFileError(NotARegularFileError): |
| 251 |
pass |
| 252 |
|
| 253 |
|
| 254 |
class IsDirectoryError(MissingFileError): |
| 255 |
pass |
| 256 |
|
| 257 |
|
| 258 |
class FileEntry: |
| 259 |
__slots__ = ("path", "size", "mtime") |
| 260 |
|
| 261 |
def __init__(self, path, stat_cache=None): |
| 262 |
self.path = path |
| 263 |
stat_function = os.stat if stat_cache is None else stat_cache.__getitem__ |
| 264 |
stat = self.stat_regular_file(path, stat_function) |
| 265 |
self.size = stat.st_size |
| 266 |
self.mtime = stat.st_mtime |
| 267 |
|
| 268 |
@staticmethod |
| 269 |
def stat_regular_file(path, stat_function): |
| 270 |
""" |
| 271 |
Wrap `stat_function` to raise appropriate errors if `path` is not a |
| 272 |
regular file |
| 273 |
""" |
| 274 |
try: |
| 275 |
stat_result = stat_function(path) |
| 276 |
except KeyError: |
| 277 |
raise MissingFileError(path) |
| 278 |
except OSError as e: |
| 279 |
if e.errno in (errno.ENOENT, errno.ENAMETOOLONG): |
| 280 |
raise MissingFileError(path) |
| 281 |
else: |
| 282 |
raise |
| 283 |
if not stat.S_ISREG(stat_result.st_mode): |
| 284 |
if stat.S_ISDIR(stat_result.st_mode): |
| 285 |
raise IsDirectoryError(f"Path is a directory: {path}") |
| 286 |
else: |
| 287 |
raise NotARegularFileError(f"Not a regular file: {path}") |
| 288 |
return stat_result |