#!/usr/bin/env python3
"""Temporarily change HTTP/2 in Nginx's included Plesk configuration files."""
import argparse
import difflib
import os
import re
import subprocess
import sys
import tempfile
from pathlib import Path
CONFIG_FILE = re.compile(rb"(?m)^# configuration file (.+):$")
HTTP2_ON = re.compile(rb"(?m)^([ \t]*http2[ \t]+)on(?=[ \t]*;)")
HTTP2_OFF = re.compile(rb"(?m)^([ \t]*http2[ \t]+)off(?=[ \t]*;)")
LISTEN = re.compile(rb"(?m)^[ \t]*listen[ \t]+[^#;\r\n]+;")
LEGACY_HTTP2 = re.compile(rb"[ \t]+http2(?=[ \t;])")
LEGACY_MARKER = b" # plesk-nginx-http2: restore listen http2"
DISABLED_LISTEN = re.compile(
rb"(?m)^([ \t]*listen[ \t]+[^#;\r\n]+);"
+ re.escape(LEGACY_MARKER)
+ rb"(?=[ \t\r\n#]|$)"
)
def included_files():
dump = subprocess.check_output(["nginx", "-T"])
paths = {Path(os.fsdecode(name)).resolve(strict=True)
for name in CONFIG_FILE.findall(dump)}
if not paths:
raise ValueError("Could not identify included files in nginx -T output.")
return paths
def disable_http2(config, mark_legacy=True):
def disable_listen(match):
directive = match[0]
disabled = LEGACY_HTTP2.sub(b"", directive)
return disabled + LEGACY_MARKER if mark_legacy and disabled != directive else disabled
config = HTTP2_ON.sub(rb"\g<1>off", config)
return LISTEN.sub(disable_listen, config)
def enable_http2(path, current, backup):
if backup is None:
enabled = HTTP2_OFF.sub(rb"\g<1>on", current)
return DISABLED_LISTEN.sub(rb"\g<1> http2;", enabled)
saved = backup / path.relative_to("/")
if not saved.is_file():
return current
original = saved.read_bytes()
if current == original:
return current
if current not in (disable_http2(original), disable_http2(original, mark_legacy=False)):
raise ValueError(
f"{path} differs from the disabled version of {saved}. "
"Compare the two files and restore the HTTP/2 directives manually "
"to preserve other changes."
)
return original
def show_changes(changes):
for path, before, after in changes:
name = os.fsencode(path)
diff = difflib.diff_bytes(
difflib.unified_diff,
before.splitlines(keepends=True),
after.splitlines(keepends=True),
fromfile=name + b" (current)",
tofile=name + b" (proposed)",
n=0,
)
for line in diff:
sys.stdout.buffer.write(line if line.endswith(b"\n") else line + b"\n")
sys.stdout.buffer.flush()
print(f"Staging: {len(changes)} file(s) would change.")
def apply_changes(changes):
backup = Path(tempfile.mkdtemp(prefix="nginx-http2-", dir="/root"))
for path, before, _ in changes:
saved = backup / path.relative_to("/")
saved.parent.mkdir(parents=True, exist_ok=True)
saved.write_bytes(before)
print(f"Backup of {len(changes)} file(s): {backup}", flush=True)
attempted = []
try:
for path, before, after in changes:
if path.resolve(strict=True) != path or path.read_bytes() != before:
raise ValueError(f"{path} changed during the run.")
# Modify the resolved file in place to preserve its metadata and aliases.
attempted.append((path, before, after))
path.write_bytes(after)
subprocess.run(["nginx", "-t"], check=True)
except (OSError, ValueError, subprocess.CalledProcessError, KeyboardInterrupt):
for path, before, after in reversed(attempted):
try:
current = path.read_bytes()
# A failed write may leave a prefix of the intended contents.
if path.resolve(strict=True) != path or not after.startswith(current):
print(f"{path} changed during rollback. See {backup}.", file=sys.stderr)
else:
path.write_bytes(before)
except OSError as error:
print(f"Could not restore {path}: {error}. See {backup}.", file=sys.stderr)
raise
def main():
parser = argparse.ArgumentParser(description=__doc__)
modes = parser.add_subparsers(dest="mode")
disable = modes.add_parser("disable", help="Disable HTTP/2 in included files")
enable = modes.add_parser("enable", help="Enable HTTP/2 in included files")
enable.add_argument("--from-backup", type=Path, metavar="DIRECTORY",
help="Restore the original HTTP/2 settings from a disable run")
for mode in (disable, enable):
mode.add_argument("--dry-run", "--stage", action="store_true",
help="Show the diff without editing files or restarting Nginx")
args = parser.parse_args()
if args.mode is None:
parser.error("Choose disable or enable.")
backup = args.from_backup if args.mode == "enable" else None
if backup is not None and not backup.is_dir():
parser.error(f"Backup directory does not exist: {backup}")
changes = []
for path in sorted(included_files()):
before = path.read_bytes()
after = (disable_http2(before) if args.mode == "disable"
else enable_http2(path, before, backup))
if before != after:
changes.append((path, before, after))
if args.dry_run:
show_changes(changes)
elif changes:
apply_changes(changes)
try:
subprocess.run(["systemctl", "restart", "nginx"], check=True)
except (OSError, subprocess.CalledProcessError):
print("The validated configuration is on disk, but Nginx restart failed.",
file=sys.stderr)
raise
else:
print("No files need changing.")
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, subprocess.CalledProcessError) as error:
sys.exit(str(error))
except KeyboardInterrupt:
sys.exit(130)