import fcntl import grp import json import os import pwd import socket import stat import subprocess import time from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from .node_files import ( check_root_file, read_root_file, require_root_directory, write_new_file, ) from .php_runtime import ( DEFAULT_PHP_RUNTIME, PHP_SERIES, PhpRuntime, available_php_versions, ) STATE_DIRECTORY = Path("/var/lib/coulobre/web-node") WEB_ROOT = Path("/srv/coulobre/web") APACHE_AVAILABLE = Path("/etc/apache2/sites-available") APACHE_ENABLED = Path("/etc/apache2/sites-enabled") SITE_SHELL = "/usr/sbin/nologin" STARTER_PAGE = ( '' "
Upload your website files to replace this page.
" "\n" ) @dataclass(frozen=True) class SitePaths: account: Path apache: Path enabled: Path pool: Path socket: Path runtime: PhpRuntime = DEFAULT_PHP_RUNTIME routed: bool = False @property def route(self): # This route survives PHP service restarts and reboots. return self.account / ".coulobre-php.sock" @property def apache_socket(self): return self.route if self.routed else self.socket @classmethod def for_site(cls, site, *, version=None, archived_account=None): configuration = site.configuration() name = configuration["service_user"] account = WEB_ROOT / site.node_key socket = Path(configuration["socket_path"]) runtime = DEFAULT_PHP_RUNTIME route = (archived_account or account) / ".coulobre-php.sock" routed = version is not None or os.path.lexists(route) if version is not None: runtime = PhpRuntime(version) socket = socket.with_name(f"{name}-{version}.sock") elif routed: require_root_directory(route.parent) info = route.lstat() if not stat.S_ISLNK(info.st_mode) or info.st_uid != 0: raise ValueError( f"Expected a root-owned PHP route at {route}." ) target = route.readlink() series = target.stem.removeprefix(f"{name}-") if target != socket: if not ( PHP_SERIES.fullmatch(series) and target == socket.with_name(f"{name}-{series}.sock") ): raise ValueError(f"Unexpected PHP socket at {route}.") runtime = PhpRuntime(series) socket = target return cls( account=account, apache=APACHE_AVAILABLE / f"{name}.conf", enabled=APACHE_ENABLED / f"{name}.conf", pool=runtime.pools / f"{name}.conf", socket=socket, runtime=runtime, routed=routed, ) @contextmanager def locked_web_node(mode): try: require_root_directory(STATE_DIRECTORY) except FileNotFoundError: raise ValueError( "Apply the site manifest on the web node first." ) from None lock_path = STATE_DIRECTORY / "apply.lock" check_root_file(lock_path) with lock_path.open("r") as lock: fcntl.flock(lock, mode) yield def apply_site(site, *, php_settings=None): applied, _ = apply_site_with_runtime(site, php_settings=php_settings) return applied def apply_site_with_runtime( site, *, php_settings=None, allowed=(), starter_page=False ): if os.geteuid() != 0: raise ValueError("Run apply as root on the web node.") for directory in (APACHE_AVAILABLE, APACHE_ENABLED): require_root_directory(directory) require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750) require_root_directory(STATE_DIRECTORY, create_mode=0o700) require_root_directory(WEB_ROOT.parent, create_mode=0o755) require_root_directory(WEB_ROOT, create_mode=0o755) with (STATE_DIRECTORY / "apply.lock").open("a") as lock: fcntl.flock(lock, fcntl.LOCK_EX) return install_site( site, php_settings=php_settings, allowed=allowed, starter_page=starter_page, ) def install_site(site, *, php_settings=None, allowed=(), starter_page=False): user = site.configuration()["service_user"] paths = SitePaths.for_site(site) create_route = not ( paths.routed or ( os.path.lexists(STATE_DIRECTORY / f"{site.node_key}.json") and (os.path.lexists(paths.apache) or os.path.lexists(paths.pool)) ) ) if create_route: versions = available_php_versions(allowed) if not versions: raise ValueError( "Install a stable PHP-FPM series allowed for this site." ) paths = SitePaths.for_site(site, version=versions[0]) require_root_directory(paths.pool.parent) owned_paths = ( paths.account, paths.apache, paths.enabled, paths.pool, paths.socket, ) check_services(paths.runtime) reserve_account(site, user, owned_paths) uid, web_gid = ensure_system_account(user, paths.account) require_root_directory(paths.account, create_mode=0o755) document_root = paths.account / "public" ensure_public_directory(document_root, uid, web_gid) if starter_page: install_starter_page(document_root, uid, web_gid) if create_route: paths.route.symlink_to(paths.socket) applied = install_configurations(site, paths, php_settings=php_settings) return applied, paths.runtime.version def install_starter_page(document_root, uid, gid): directory = os.open( document_root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW ) try: if os.listdir(directory): return try: file = os.open( "index.html", os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644, dir_fd=directory, ) except FileExistsError: return with os.fdopen(file, "w", encoding="utf-8") as page: page.write(STARTER_PAGE) page.flush() os.fchown(page.fileno(), uid, gid) os.fchmod(page.fileno(), 0o644) finally: os.close(directory) def site_status(site): if os.geteuid() != 0: raise ValueError("Run status as root on the web node.") report = {**site.manifest(), "state": "not_installed", "problem": None} try: require_root_directory(STATE_DIRECTORY) except FileNotFoundError: return report marker = STATE_DIRECTORY / f"{site.node_key}.json" if not os.path.lexists(marker): return report with (STATE_DIRECTORY / "apply.lock").open("r") as lock: fcntl.flock(lock, fcntl.LOCK_SH) try: check_reservation(site) paths = SitePaths.for_site(site) check_installation(site, paths) except (OSError, ValueError) as error: return { **report, "state": "needs_attention", "problem": str(error), } return { **report, "state": "configured", "php_version": paths.runtime.version, } def check_reservation(site): marker = STATE_DIRECTORY / f"{site.node_key}.json" try: saved = json.loads(read_root_file(marker)) except FileNotFoundError: raise ValueError( "Apply the site manifest before using its document root." ) from None if saved != site.manifest(): raise ValueError("The account is reserved with a different manifest.") def site_storage(site): check_reservation(site) account = WEB_ROOT / site.node_key require_root_directory(account) user = site.configuration()["service_user"] uid, gid = check_system_account(user, account) public = account / "public" check_public_directory(public, uid, gid) return public, uid, gid def check_installation(site, paths): from .web_node_php import read_managed_php_pool for directory in ( paths.account, APACHE_AVAILABLE, APACHE_ENABLED, paths.pool.parent, ): require_root_directory(directory) user = site.configuration()["service_user"] uid, gid = check_system_account(user, paths.account) check_public_directory(paths.account / "public", uid, gid) check_configuration( paths.apache, site.render("apache", socket_path=paths.apache_socket) ) read_managed_php_pool(site, paths.pool, socket_path=paths.socket) check_site_link( paths.enabled, Path("../sites-available") / paths.apache.name ) check_services(paths.runtime) if not socket_exists(paths.socket): raise ValueError( f"PHP-FPM is missing the site socket at {paths.socket}." ) return uid, gid def check_services(runtime): for service in (runtime.service, "apache2"): run("/usr/sbin/service", service, "status") if "proxy_fcgi_module" not in run("/usr/sbin/apache2ctl", "-M"): raise ValueError("Enable Apache's proxy_fcgi module on the web node.") def reserve_account(site, user, paths): from .wordpress_staging_publication import check_staging_hostname_available reject_tool_hostname(site.domain) check_staging_hostname_available(site.domain) marker = STATE_DIRECTORY / f"{site.node_key}.json" if os.path.lexists(marker.with_suffix(".retired")): raise ValueError("This website belongs to a retired hosting account.") manifest = site.manifest() for existing in STATE_DIRECTORY.glob("*.json"): saved = json.loads(read_root_file(existing)) if existing == marker: if saved != manifest: raise ValueError( "The website is already reserved with a different " "manifest." ) elif saved["domain"] == site.domain: raise ValueError( "The primary domain is already reserved by another account." ) from .web_node_aliases import ( check_alias_domain_available, check_apache_hostname_available, ) check_alias_domain_available(site.domain) if os.path.lexists(marker): return if ( current_user(user) or current_group(user) or any(os.path.lexists(p) for p in paths) ): raise ValueError( "The web node already has unmanaged resources for this account." ) if site.site_id is not None: check_apache_hostname_available(site.domain) write_new_file(marker, json.dumps(manifest) + "\n", mode=0o600) def reject_tool_hostname(hostname, *, except_site=None): for tool in ("phpmyadmin", "roundcube"): site = APACHE_AVAILABLE / f"coulobre-{tool}.conf" if site == except_site: continue try: configuration = read_root_file(site) except FileNotFoundError: continue for line in configuration.splitlines(): directive = line.split() if ( len(directive) == 2 and directive[0].lower() == "servername" and directive[1].lower().rstrip(".") == hostname ): raise ValueError("This hostname is reserved for a panel tool.") def current_user(name): try: return pwd.getpwnam(name) except KeyError: return None def current_group(name): try: return grp.getgrnam(name) except KeyError: return None def ensure_system_account(user, account_dir): if current_user(user) is None: group_options = ("--user-group",) group = current_group(user) if group is not None: if group.gr_mem or not group.gr_gid: raise ValueError( f"Unexpected members or ID in the {user} group." ) group_options = ("--gid", str(group.gr_gid)) run( "/usr/sbin/useradd", "--system", *group_options, "--no-create-home", "--home-dir", str(account_dir), "--shell", SITE_SHELL, user, ) return check_system_account(user, account_dir) def check_system_account(user, account_dir): account = current_user(user) group = current_group(user) if ( account is None or not account.pw_uid or group is None or not group.gr_gid or group.gr_mem or account.pw_gid != group.gr_gid or account.pw_dir != str(account_dir) or account.pw_shell != SITE_SHELL ): raise ValueError(f"Unexpected user or group configuration for {user}.") web_group = current_group("www-data") if web_group is None: raise ValueError("The Apache www-data group is missing.") return account.pw_uid, web_group.gr_gid def ensure_public_directory(path, uid, gid): if not os.path.lexists(path): path.mkdir(mode=0o700) info = path.lstat() if ( stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not any(path.iterdir()) ): path.chmod(0o750) os.chown(path, uid, gid, follow_symlinks=False) check_public_directory(path, uid, gid) def check_public_directory(path, uid, gid): info = path.lstat() if ( not stat.S_ISDIR(info.st_mode) or (info.st_uid, info.st_gid) != (uid, gid) or stat.S_IMODE(info.st_mode) != 0o750 ): raise ValueError(f"Unexpected ownership or mode for {path}.") def install_configurations(site, paths, *, php_settings=None): from .php_pool_settings import PhpPoolSettings from .web_node_php import read_managed_php_pool apache_socket = paths.apache_socket if paths.routed else None pool_socket = paths.socket if paths.routed else None with configuration_installation() as (created, reload_attempts): install_configuration( paths.apache, site.render("apache", socket_path=apache_socket), created, ) if os.path.lexists(paths.pool): _, applied = read_managed_php_pool( site, paths.pool, socket_path=pool_socket ) else: applied = php_settings or PhpPoolSettings() install_configuration( paths.pool, site.render( "php-fpm", php_settings=applied, socket_path=pool_socket ), created, ) enable_apache_site(paths.apache, paths.enabled, created) run(paths.runtime.binary, "--test") run("/usr/sbin/apache2ctl", "configtest") reload_attempts.append(paths.runtime.service) run("/usr/sbin/service", paths.runtime.service, "reload") wait_for_socket(paths.socket) reload_attempts.append("apache2") run("/usr/sbin/service", "apache2", "reload") return applied def install_configuration(path, content, created): if os.path.lexists(path): check_configuration(path, content) else: write_new_file(path, content, mode=0o644) created.append(path) def enable_apache_site(apache, enabled, created): link_target = Path("../sites-available") / apache.name if os.path.lexists(enabled): check_site_link(enabled, link_target) else: enabled.symlink_to(link_target) created.append(enabled) @contextmanager def configuration_installation(): created = [] reload_attempts = [] try: yield created, reload_attempts except (OSError, ValueError, KeyboardInterrupt) as error: failures = [] for path in reversed(created): try: path.unlink(missing_ok=True) except OSError as rollback_error: failures.append(str(rollback_error)) for service in reload_attempts: try: run("/usr/sbin/service", service, "reload") except (OSError, ValueError) as rollback_error: failures.append(str(rollback_error)) if failures: raise ValueError( f"{error}\nRollback errors:\n" + "\n".join(failures) ) from error raise def check_configuration(path, content): from .web_redirects import compatible_configs if read_root_file(path) not in compatible_configs(content): raise ValueError(f"Existing configuration differs at {path}.") def check_site_link(enabled, target): if not enabled.is_symlink() or enabled.readlink() != target: raise ValueError( f"Expected the Apache site link at {enabled} to point to {target}." ) def wait_for_socket(path): deadline = time.monotonic() + 15 while time.monotonic() < deadline: if socket_exists(path): with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe: probe.settimeout(0.1) try: probe.connect(str(path)) except OSError: pass else: return time.sleep(0.1) raise ValueError(f"PHP-FPM did not open {path}.") def socket_exists(path): try: return stat.S_ISSOCK(path.lstat().st_mode) except FileNotFoundError: return False def run(*command): process = subprocess.run( command, capture_output=True, text=True, env={"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LANG": "C"}, ) if process.returncode: message = process.stderr.strip() or process.stdout.strip() raise ValueError( f"{' '.join(command)} failed ({process.returncode}). {message}" ) return process.stdout