Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
121 lines (97 loc) · 4.16 KB
/
Copy pathserver.py
File metadata and controls
121 lines (97 loc) · 4.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""Local HTTP dev server with COOP/COEP headers and RFC 7233 Range support."""
import http.server
import os
import socketserver
import urllib.parse
from scripts.http_range_core import ByteRange, RangeUnsatisfiable, parse_byte_range
DEFAULT_PORT = 8000
CHUNK_SIZE = 64 * 1024
def get_server_port() -> int:
"""Read port from PORT environment variable, falling back to 8000."""
raw = os.environ.get("PORT", str(DEFAULT_PORT)).strip()
return int(raw) if raw.isdigit() else DEFAULT_PORT
class RangeCOIHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):
"""HTTP handler serving static assets with COOP/COEP/CORP and HTTP Range."""
extensions_map = {
**http.server.SimpleHTTPRequestHandler.extensions_map,
".mjs": "application/javascript",
".js": "application/javascript",
".wasm": "application/wasm",
".erofs": "application/octet-stream",
".json": "application/json",
}
def end_headers(self) -> None:
self.send_header("Cross-Origin-Opener-Policy", "same-origin")
self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
self.send_header("Cache-Control", "no-store, no-cache, must-revalidate")
super().end_headers()
def do_GET(self) -> None:
self._handle_request(send_body=True)
def do_HEAD(self) -> None:
self._handle_request(send_body=False)
def _handle_request(self, *, send_body: bool) -> None:
path = self.translate_path(self.path)
if os.path.isdir(path) or not os.path.isfile(path):
if send_body:
super().do_GET()
else:
super().do_HEAD()
return
file_size = os.path.getsize(path)
range_header = self.headers.get("Range")
parsed = parse_byte_range(range_header, file_size)
if isinstance(parsed, RangeUnsatisfiable):
self.send_response(416, "Range Not Satisfiable")
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Range", parsed.content_range_header)
self.send_header("Content-Length", "0")
self.end_headers()
return
ctype = self.guess_type(path)
stat_res = os.stat(path)
if isinstance(parsed, ByteRange):
self.send_response(206, "Partial Content")
self.send_header("Content-Type", ctype)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Range", parsed.content_range_header)
self.send_header("Content-Length", str(parsed.length))
self.send_header("Last-Modified", self.date_time_string(stat_res.st_mtime))
self.end_headers()
if send_body:
self._send_file_slice(path, parsed.start, parsed.length)
return
self.send_response(200)
self.send_header("Content-Type", ctype)
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", str(file_size))
self.send_header("Last-Modified", self.date_time_string(stat_res.st_mtime))
self.end_headers()
if send_body:
self._send_file_slice(path, 0, file_size)
def _send_file_slice(self, path: str, start: int, length: int) -> None:
remaining = length
with open(path, "rb") as fh:
fh.seek(start)
while remaining > 0:
chunk = fh.read(min(CHUNK_SIZE, remaining))
if not chunk:
break
self.wfile.write(chunk)
remaining -= len(chunk)
class ThreadingTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True
daemon_threads = True
def main() -> None:
port = get_server_port()
with ThreadingTCPServer(("127.0.0.1", port), RangeCOIHTTPRequestHandler) as httpd:
print(
f"Serving HTTP on http://127.0.0.1:{port} "
"(COOP/COEP + HTTP Range enabled)..."
)
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("\nStopping server.")
if __name__ == "__main__":
main()