#!/usr/bin/env python3 """Safely normalize school-domain HTTP links to HTTPS. The script never rewrites third-party HTTP URLs automatically. It writes a report with external hosts so they can be reviewed separately. """ from __future__ import annotations import argparse import collections import hashlib import json import os import re import shutil import stat import tempfile from pathlib import Path TEXT_SUFFIXES = { ".css", ".htm", ".html", ".jsp", ".jspf", ".js", ".json", ".properties", ".txt", ".vue", ".xml", } MAX_BYTES = 32 * 1024 * 1024 SCHOOL_URL = re.compile( r"http://(?P(?:[A-Za-z0-9-]+\.)*gzhxtc\.edu\.cn)(?::(?P\d+))?", re.IGNORECASE, ) SPECIAL_REWRITES = ( (re.compile(r"http://xg\.gzhxtc\.edu\.cn:4106/", re.IGNORECASE), "https://xg.gzhxtc.edu.cn/"), ) ANY_HTTP_URL = re.compile(r"http://(?P[^/\s\"'<>?#]+)", re.IGNORECASE) def decode_text(data: bytes) -> tuple[str, str]: if data.startswith(b"\xef\xbb\xbf"): return data.decode("utf-8-sig"), "utf-8-sig" if data.startswith((b"\xff\xfe", b"\xfe\xff")): return data.decode("utf-16"), "utf-16" for encoding in ("utf-8", "gb18030"): try: return data.decode(encoding), encoding except UnicodeDecodeError: continue raise UnicodeDecodeError("unknown", b"", 0, 1, "unsupported text encoding") def rewrite_school_urls(text: str) -> tuple[str, int]: count = 0 for pattern, replacement in SPECIAL_REWRITES: text, special_count = pattern.subn(replacement, text) count += special_count def replace(match: re.Match[str]) -> str: nonlocal count port = match.group("port") if port and port not in {"80", "443"}: return match.group(0) count += 1 suffix = ":443" if port == "443" else "" return f"https://{match.group('host')}{suffix}" return SCHOOL_URL.sub(replace, text), count def collect_external_hosts(text: str, host_counts: collections.Counter[str], samples: dict[str, str]) -> None: for match in ANY_HTTP_URL.finditer(text): host = match.group("host").lower() host_name = host.rsplit(":", 1)[0] if ":" in host else host if host_name.endswith(".gzhxtc.edu.cn") or host_name == "gzhxtc.edu.cn": continue host_counts[host] += 1 samples.setdefault(host, match.group(0)) def phase_roots(root: Path, phase: str) -> list[Path]: if phase == "templates": candidates = [ "web/subassembly/website", "web/upload/ffkj-template", "main", "WEB-INF", "apps", "js", "css", ] elif phase == "content": candidates = ["web/upload"] else: candidates = phase_roots(root, "templates") + phase_roots(root, "content") return [root / candidate for candidate in candidates if (root / candidate).exists()] def iter_text_files(roots: list[Path], phase: str, root: Path) -> list[Path]: seen: set[Path] = set() files: list[Path] = [] template_upload = (root / "web/upload/ffkj-template").resolve() for base in roots: for path in base.rglob("*"): if not path.is_file() or path.suffix.lower() not in TEXT_SUFFIXES: continue if path.name.startswith("._") or any( part.lower() == "backup" or part == ".zq-quarantine" or part.startswith(".zq-stage-") for part in path.parts ): continue resolved = path.resolve() if phase == "content" and (resolved == template_upload or template_upload in resolved.parents): continue try: if path.stat().st_size > MAX_BYTES: continue except OSError: continue if resolved not in seen: seen.add(resolved) files.append(path) return sorted(files) def apply_file(path: Path, root: Path, backup_root: Path, manifest) -> tuple[int, bool, str | None]: original = path.read_bytes() try: text, encoding = decode_text(original) except UnicodeDecodeError: return 0, False, "unsupported-encoding" rewritten, count = rewrite_school_urls(text) if count == 0 or rewritten == text: return 0, False, None rel = path.relative_to(root) backup_path = backup_root / rel backup_path.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(path, backup_path) new_data = rewritten.encode(encoding) mode = stat.S_IMODE(path.stat().st_mode) fd, temp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) try: with os.fdopen(fd, "wb") as handle: handle.write(new_data) os.chmod(temp_name, mode) os.replace(temp_name, path) finally: if os.path.exists(temp_name): os.unlink(temp_name) manifest.write( json.dumps( { "path": str(rel), "replacements": count, "old_sha256": hashlib.sha256(original).hexdigest(), "new_sha256": hashlib.sha256(new_data).hexdigest(), "backup": str(backup_path), }, ensure_ascii=False, ) + "\n" ) return count, True, None def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--root", required=True) parser.add_argument("--phase", choices=("templates", "content", "all"), default="all") parser.add_argument("--apply", action="store_true") parser.add_argument("--backup-root") parser.add_argument("--manifest") parser.add_argument("--report") args = parser.parse_args() root = Path(args.root).resolve() roots = phase_roots(root, args.phase) files = iter_text_files(roots, args.phase, root) host_counts: collections.Counter[str] = collections.Counter() host_samples: dict[str, str] = {} changed_files = 0 files_with_school_http = 0 school_http_files: list[dict[str, object]] = [] replacements = 0 skipped: collections.Counter[str] = collections.Counter() manifest_handle = None if args.apply: if not args.backup_root or not args.manifest: parser.error("--apply requires --backup-root and --manifest") Path(args.backup_root).mkdir(parents=True, exist_ok=True) Path(args.manifest).parent.mkdir(parents=True, exist_ok=True) manifest_handle = Path(args.manifest).open("w", encoding="utf-8") try: for path in files: try: text, _ = decode_text(path.read_bytes()) except (OSError, UnicodeDecodeError) as exc: skipped[type(exc).__name__] += 1 continue collect_external_hosts(text, host_counts, host_samples) try: if args.apply: count, changed, reason = apply_file(path, root, Path(args.backup_root), manifest_handle) else: _, count = rewrite_school_urls(text) changed, reason = False, None except OSError as exc: skipped[type(exc).__name__] += 1 continue if reason: skipped[reason] += 1 replacements += count if count: files_with_school_http += 1 school_http_files.append({"path": str(path.relative_to(root)), "count": count}) if changed: changed_files += 1 finally: if manifest_handle: manifest_handle.close() report = { "root": str(root), "phase": args.phase, "apply": args.apply, "scanned_files": len(files), "changed_files": changed_files, "files_with_school_http": files_with_school_http, "school_http_files": school_http_files, "school_http_replacements": replacements, "skipped": dict(skipped), "external_http_hosts": [ {"host": host, "count": count, "sample": host_samples.get(host, "")} for host, count in host_counts.most_common() ], } output = json.dumps(report, ensure_ascii=False, indent=2) if args.report: Path(args.report).parent.mkdir(parents=True, exist_ok=True) Path(args.report).write_text(output + "\n", encoding="utf-8") print(output) return 0 if __name__ == "__main__": raise SystemExit(main())