Files
coulobre/src/coulobre/web_node_aliases.py
T

180 lines
6.3 KiB
Python

import fcntl
import json
import os
import re
from fnmatch import fnmatchcase
from pathlib import Path
from . import web_node_apply as web
from .node_files import read_root_file, require_root_directory, write_new_file
from .web_node import WebAlias
from .web_node_tls import (
check_https_prerequisites,
delete_alias_certificate,
ensure_certificate,
install_https_configuration,
render_https_configuration,
)
APACHE_VHOST_NAME = re.compile(
r"^\s*(?:default server|port \d+ namevhost|\S+:\d+)\s+(\S+)\s+\("
)
APACHE_VHOST_ALIAS = re.compile(r"^\s*(?:wild )?alias\s+(\S+)(?:\s|$)")
def alias_directory():
return web.STATE_DIRECTORY / "aliases"
def alias_marker(alias):
return alias_directory() / f"{alias.name}.json"
def alias_paths(alias, *, https=False):
suffix = "-https" if https else ""
name = f"zz-{alias.name}{suffix}.conf"
return web.APACHE_AVAILABLE / name, web.APACHE_ENABLED / name
def read_alias(marker):
return WebAlias.from_manifest(
json.loads(read_root_file(marker, mode=0o600))
)
def check_alias_domain_available(domain, *, alias=None):
directory = alias_directory()
if not os.path.lexists(directory):
return
require_root_directory(directory)
for marker in directory.glob("*.json"):
current = read_alias(marker)
if current.domain == domain and current != alias:
raise ValueError(
"This domain is reserved as another website alias."
)
def check_apache_hostname_available(domain):
configuration = web.run("/usr/sbin/apache2ctl", "-S")
for line in configuration.splitlines():
match = APACHE_VHOST_NAME.match(line) or APACHE_VHOST_ALIAS.match(line)
if match and fnmatchcase(domain, match[1].rstrip(".").lower()):
raise ValueError("This hostname is already configured in Apache.")
def reserve_alias(alias):
for marker in web.STATE_DIRECTORY.glob("*.json"):
if json.loads(read_root_file(marker))["domain"] == alias.domain:
raise ValueError(
"This alias is already reserved as a primary domain."
)
require_root_directory(alias_directory(), create_mode=0o700)
check_alias_domain_available(alias.domain, alias=alias)
marker = alias_marker(alias)
if os.path.lexists(marker):
if read_alias(marker) != alias:
raise ValueError(
"The website alias reservation has a different identity."
)
return
if any(
os.path.lexists(path)
for paths in (alias_paths(alias), alias_paths(alias, https=True))
for path in paths
):
raise ValueError(
"The web node already has unmanaged files for this alias."
)
check_apache_hostname_available(alias.domain)
write_new_file(marker, json.dumps(alias.manifest()) + "\n", mode=0o600)
def activate_alias(alias):
if os.geteuid() != 0:
raise ValueError("Apply the website alias as root on the web node.")
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(alias.site)
web.check_installation(alias.site, web.SitePaths.for_site(alias.site))
reserve_alias(alias)
apache, enabled = alias_paths(alias)
with web.configuration_installation() as (created, reload_attempts):
web.install_configuration(apache, alias.render("apache"), created)
web.enable_apache_site(apache, enabled, created)
web.run("/usr/sbin/apache2ctl", "configtest")
reload_attempts.append("apache2")
web.run("/usr/sbin/service", "apache2", "reload")
def provision_alias_https(alias):
with web.locked_web_node(fcntl.LOCK_EX):
check_https_prerequisites(
alias.site, web.SitePaths.for_site(alias.site)
)
require_root_directory(alias_directory())
if read_alias(alias_marker(alias)) != alias:
raise ValueError(
"The website alias reservation has a different identity."
)
apache, enabled = alias_paths(alias)
web.check_configuration(apache, alias.render("apache"))
web.check_site_link(enabled, Path("../sites-available") / apache.name)
ensure_certificate(alias)
install_https_configuration(alias, *alias_paths(alias, https=True))
def remove_alias(alias):
if os.geteuid() != 0:
raise ValueError("Remove the website alias as root on the web node.")
with web.locked_web_node(fcntl.LOCK_EX):
web.check_reservation(alias.site)
for directory in (web.APACHE_AVAILABLE, web.APACHE_ENABLED):
require_root_directory(directory)
marker = alias_marker(alias)
paths = (alias_paths(alias), alias_paths(alias, https=True))
if not os.path.lexists(marker):
if any(os.path.lexists(path) for pair in paths for path in pair):
raise ValueError(
"The web node has unmanaged files for this alias."
)
return
require_root_directory(alias_directory())
if read_alias(marker) != alias:
raise ValueError(
"The website alias reservation has a different identity."
)
expected = (alias.render("apache"), render_https_configuration(alias))
links = []
for (apache, enabled), contents in zip(paths, expected, strict=True):
if os.path.lexists(apache):
web.check_configuration(apache, contents)
if os.path.lexists(enabled):
target = Path("../sites-available") / apache.name
web.check_site_link(enabled, target)
links.append((enabled, target))
disable_alias_vhosts(links)
for apache, _ in paths:
apache.unlink(missing_ok=True)
delete_alias_certificate(alias)
marker.unlink()
def disable_alias_vhosts(links):
removed = []
try:
for enabled, target in links:
enabled.unlink()
removed.append((enabled, target))
web.run("/usr/sbin/apache2ctl", "configtest")
web.run("/usr/sbin/service", "apache2", "reload")
except (OSError, ValueError, KeyboardInterrupt):
for enabled, target in removed:
enabled.symlink_to(target)
if removed:
web.run("/usr/sbin/service", "apache2", "reload")
raise