Files
douyi_guaji_main/gui/web_gui_pkg/static_handler.py
T

87 lines
3.2 KiB
Python

import os
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler
from typing import Callable
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
def serve_static(
handler: BaseHTTPRequestHandler,
*,
webui_dir: str,
rel_path: str,
log_error: Callable[[str], None],
) -> None:
rel_path = rel_path.lstrip("/")
if not rel_path:
rel_path = "index.html"
safe = os.path.normpath(rel_path).replace("\\", "/")
# 安全检查:防止路径遍历攻击
if safe.startswith("../") or safe.startswith("..\\") or ".." in safe:
handler.send_error(HTTPStatus.FORBIDDEN)
return
full = os.path.join(webui_dir, safe)
# 额外安全检查:确保文件在 WEBUI_DIR 目录内
try:
full_real = os.path.realpath(full)
webui_real = os.path.realpath(webui_dir)
if not full_real.startswith(webui_real + os.sep) and full_real != webui_real:
handler.send_error(HTTPStatus.FORBIDDEN)
return
except Exception:
handler.send_error(HTTPStatus.FORBIDDEN)
return
if not os.path.isfile(full):
handler.send_error(HTTPStatus.NOT_FOUND)
return
ext = os.path.splitext(full)[1].lower()
ctype = {
".html": "text/html; charset=utf-8",
".css": "text/css; charset=utf-8",
".js": "application/javascript; charset=utf-8",
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".svg": "image/svg+xml; charset=utf-8",
}.get(ext, "application/octet-stream")
try:
with open(full, "rb") as f:
data = f.read()
# 对于静态资源,使用适当的缓存策略
cache_control = "no-store" if ext in (".html", ".js") else "public, max-age=3600"
# 添加 ETag 支持(简单实现:基于文件大小和修改时间)
try:
stat = os.stat(full)
etag = f'"{stat.st_size}-{int(stat.st_mtime)}"'
# 检查 If-None-Match 头,支持 304 Not Modified
if_none_match = handler.headers.get("If-None-Match", "")
if if_none_match == etag:
handler.send_response(HTTPStatus.NOT_MODIFIED)
handler.send_header("ETag", etag)
handler.send_header("Cache-Control", cache_control)
send_security_headers(handler)
handler.end_headers()
return
except Exception:
etag = None
handler.send_response(HTTPStatus.OK)
handler.send_header("Content-Type", ctype)
handler.send_header("Content-Length", str(len(data)))
handler.send_header("Cache-Control", cache_control)
if ext == ".html":
send_html_security_headers(handler)
else:
send_security_headers(handler)
if etag:
handler.send_header("ETag", etag)
handler.end_headers()
handler.wfile.write(data)
except FileNotFoundError:
handler.send_error(HTTPStatus.NOT_FOUND)
except Exception as e:
log_error(f"[WEB_GUI] Error serving static file {rel_path}: {e}")
handler.send_error(HTTPStatus.INTERNAL_SERVER_ERROR)