from __future__ import annotations import hashlib import hmac import ipaddress import os import re import secrets import shutil import subprocess import tempfile import threading from dataclasses import dataclass from datetime import datetime from pathlib import Path from urllib.parse import urlsplit from flask import Flask, Response, abort, flash, redirect, render_template_string, request, session, url_for # ----------------------------------------------------------------------------- # Configuration # ----------------------------------------------------------------------------- CADDYFILE = Path(os.getenv("CADDYFILE", "/etc/caddy/Caddyfile")).resolve() DNSMASQ_CONF = Path(os.getenv("DNSMASQ_CONF", "/etc/dnsmasq.conf")).resolve() BACKUP_DIR = Path(os.getenv("BACKUP_DIR", "/var/backups/web-proxy-config")) BEGIN_MARKER = os.getenv("BEGIN_MARKER", "#begin marker") END_MARKER = os.getenv("END_MARKER", "#end marker") def env_bool(name: str, default: bool) -> bool: raw = os.getenv(name) if raw is None: return default return raw.strip().lower() in {"1", "true", "yes", "on"} AUTH_ENABLED = env_bool("AUTH_ENABLED", True) ADMIN_USER = os.getenv("ADMIN_USER", "admin") ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "") APP_SECRET = os.getenv("APP_SECRET", secrets.token_urlsafe(48)) DNSMASQ_TARGET_IP = str( ipaddress.ip_address(os.getenv("DNSMASQ_TARGET_IP", "192.168.7.251").strip()) ) MAX_IMPORT_BYTES = int(os.getenv("MAX_IMPORT_BYTES", str(256 * 1024))) LAN_NETWORKS = [ x.strip() for x in os.getenv("LAN_NETWORKS", "192.168.7.0/24,10.10.10.0/24").split(",") if x.strip() ] MAX_BACKUPS = int(os.getenv("MAX_BACKUPS", "50")) CADDY_VALIDATE_CMD = [ os.getenv("CADDY_BIN", "/usr/bin/caddy"), "validate", "--config", str(CADDYFILE), "--adapter", "caddyfile", ] CADDY_APPLY_CMD = ["/usr/bin/systemctl", "reload", "caddy"] DNSMASQ_VALIDATE_CMD = [ os.getenv("DNSMASQ_BIN", "/usr/sbin/dnsmasq"), "--test", f"--conf-file={DNSMASQ_CONF}", ] DNSMASQ_APPLY_CMD = ["/usr/bin/systemctl", "restart", "dnsmasq"] if AUTH_ENABLED and not ADMIN_PASSWORD: raise RuntimeError( "AUTH_ENABLED is true, but ADMIN_PASSWORD is not configured. " "Set ADMIN_PASSWORD or disable authentication with AUTH_ENABLED=false." ) app = Flask(__name__) app.secret_key = APP_SECRET app.config.update( SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Strict", ) CHANGE_LOCK = threading.Lock() # ----------------------------------------------------------------------------- # Models / parsing # ----------------------------------------------------------------------------- @dataclass class CaddyRecord: record_id: str site: str target: str comment: str lan_only: bool start: int end: int raw: str @dataclass class DnsRecord: record_id: str domain: str ip: str address_index: int local_indices: tuple[int, ...] ipv6_blocked: bool raw: str def _hash_id(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16] def _find_marker_line(text: str, marker: str) -> list[re.Match[str]]: pattern = re.compile( rf"(?im)^[ \t]*{re.escape(marker.strip())}[ \t]*(?:\r\n|\n|\r|$)" ) return list(pattern.finditer(text)) def split_managed_section(text: str) -> tuple[str, str, str, str]: """Return prefix, managed text, suffix and preferred newline. Prefix includes the begin-marker line and its line ending. Suffix starts with the end-marker line. Therefore prefix and suffix can be copied byte-for-byte (at the decoded text level) without being rebuilt. """ begins = _find_marker_line(text, BEGIN_MARKER) ends = _find_marker_line(text, END_MARKER) if len(begins) != 1 or len(ends) != 1: raise ValueError( f"Expected exactly one '{BEGIN_MARKER}' and one '{END_MARKER}' marker." ) begin = begins[0] end = ends[0] if end.start() < begin.end(): raise ValueError("End marker is before the begin marker.") prefix = text[: begin.end()] managed = text[begin.end() : end.start()] suffix = text[end.start() :] if prefix.endswith("\r\n"): newline = "\r\n" elif prefix.endswith("\n"): newline = "\n" elif prefix.endswith("\r"): newline = "\r" else: newline = "\n" return prefix, managed, suffix, newline def get_managed_lines(text: str) -> list[str]: _, managed, _, _ = split_managed_section(text) return managed.splitlines() def replace_managed_lines(text: str, managed: list[str]) -> str: prefix, _, suffix, newline = split_managed_section(text) body = newline.join(managed) if body: body += newline return prefix + body + suffix def read_text_exact(path: Path) -> str: with path.open("r", encoding="utf-8", newline="") as fh: return fh.read() def _brace_delta(line: str) -> int: """Count braces outside double quotes/backticks and before comments.""" delta = 0 quote = None escaped = False for ch in line: if escaped: escaped = False continue if ch == "\\" and quote == '"': escaped = True continue if quote: if ch == quote: quote = None continue if ch in ('"', "`"): quote = ch continue if ch == "#": break if ch == "{": delta += 1 elif ch == "}": delta -= 1 return delta def parse_caddy_records(managed: list[str]) -> list[CaddyRecord]: records: list[CaddyRecord] = [] i = 0 while i < len(managed): stripped = managed[i].strip() if not stripped or stripped.startswith("#") or "{" not in managed[i]: i += 1 continue header = managed[i].split("{", 1)[0].strip() if not header: i += 1 continue depth = 0 end = i found_open = False for j in range(i, len(managed)): d = _brace_delta(managed[j]) if d > 0: found_open = True depth += d end = j if found_open and depth == 0: break else: # Let caddy validate report the malformed structure; don't make it deletable. i += 1 continue # Attach immediately preceding comment lines to this record so delete is tidy. start = i k = i - 1 while k >= 0 and managed[k].strip().startswith("#"): start = k k -= 1 raw_lines = managed[start : end + 1] raw = "\n".join(raw_lines) comments = [ line.strip()[1:].strip() for line in managed[start:i] if line.strip().startswith("#") ] comment = " / ".join(x for x in comments if x) m = re.search(r"(?m)^\s*reverse_proxy\s+([^\s{]+)", raw) target = m.group(1) if m else "—" lan_only = bool(re.search(r"(?m)^\s*@\w+\s+remote_ip\s+", raw)) records.append( CaddyRecord( record_id=_hash_id(raw), site=header, target=target, comment=comment, lan_only=lan_only, start=start, end=end, raw=raw, ) ) i = end + 1 return records DNS_ADDRESS_RE = re.compile(r"^\s*address=/([^/]+)/([^/\s]+)\s*$") DNS_LOCAL_RE = re.compile(r"^\s*local=/([^/]+)/\s*$") def parse_dns_local_indices(managed: list[str]) -> dict[str, list[int]]: local_indices: dict[str, list[int]] = {} for idx, line in enumerate(managed): m = DNS_LOCAL_RE.match(line) if not m: continue local_indices.setdefault(m.group(1).lower(), []).append(idx) return local_indices def parse_dns_records(managed: list[str]) -> list[DnsRecord]: records: list[DnsRecord] = [] local_indices = parse_dns_local_indices(managed) for idx, line in enumerate(managed): m = DNS_ADDRESS_RE.match(line) if not m: continue domain = m.group(1) matching_local = tuple(local_indices.get(domain.lower(), [])) records.append( DnsRecord( record_id=_hash_id(line), domain=domain, ip=m.group(2), address_index=idx, local_indices=matching_local, ipv6_blocked=bool(matching_local), raw=line, ) ) return records def append_dns_lines(managed: list[str], lines: list[str]) -> None: # Trailing blank lines inside the managed section are cosmetic. Remove them # before appending so every logical dnsmasq entry stays compact. while managed and not managed[-1].strip(): managed.pop() managed.extend(lines) # ----------------------------------------------------------------------------- # Validation helpers # ----------------------------------------------------------------------------- HOST_RE = re.compile( r"^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", re.IGNORECASE, ) DOMAIN_RE = re.compile( r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$", re.IGNORECASE, ) def validate_site(value: str) -> str: value = value.strip().lower().rstrip(".") if not HOST_RE.fullmatch(value): raise ValueError("Invalid Caddy hostname.") return value def validate_upstream(value: str) -> str: value = value.strip() try: parsed = urlsplit(value) except ValueError as exc: raise ValueError("Invalid upstream URL.") from exc if parsed.scheme not in {"http", "https"}: raise ValueError("Upstream must start with http:// or https://") if not parsed.hostname: raise ValueError("Upstream must contain a hostname or IP address.") if parsed.username or parsed.password: raise ValueError("Credentials in upstream URL are not allowed.") if parsed.path not in {"", "/"} or parsed.query or parsed.fragment: raise ValueError("Upstream must not contain a path, query, or fragment.") try: port = parsed.port except ValueError as exc: raise ValueError("Invalid upstream port.") from exc if port is not None and not (1 <= port <= 65535): raise ValueError("Invalid upstream port.") return value.rstrip("/") def validate_comment(value: str) -> str: value = " ".join(value.replace("\r", " ").replace("\n", " ").split()).strip() if len(value) > 120: raise ValueError("Comment is too long (max 120 characters).") return value def validate_dns_domain(value: str) -> str: value = value.strip().lower().rstrip(".") leading_dot = value.startswith(".") bare = value[1:] if leading_dot else value if not DOMAIN_RE.fullmatch(bare): raise ValueError("Invalid dnsmasq domain.") return ("." if leading_dot else "") + bare def validate_ip(value: str) -> str: value = value.strip() try: return str(ipaddress.ip_address(value)) except ValueError as exc: raise ValueError("Invalid IP address.") from exc def build_caddy_block(site: str, upstream: str, comment: str, lan_only: bool) -> list[str]: lines: list[str] = [] if comment: lines.append(f"#{comment}") lines.append(f"{site} {{") if lan_only: networks = " ".join(LAN_NETWORKS) lines.extend( [ f" @lan remote_ip {networks}", "", " handle @lan {", f" reverse_proxy {upstream}", " }", "", ' respond "Forbidden" 403', ] ) else: lines.append(f" reverse_proxy {upstream}") lines.append("}") return lines # ----------------------------------------------------------------------------- # File transaction / commands # ----------------------------------------------------------------------------- def run_cmd(cmd: list[str], timeout: int = 20) -> tuple[bool, str]: try: cp = subprocess.run( cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, check=False, env={**os.environ, "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"}, ) output = (cp.stdout or "").strip() return cp.returncode == 0, output or f"exit code {cp.returncode}" except (OSError, subprocess.TimeoutExpired) as exc: return False, str(exc) def atomic_write(path: Path, content: str, original_stat: os.stat_result | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) if original_stat is None: original_stat = path.stat() fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent), text=True) tmp = Path(tmp_name) try: with os.fdopen(fd, "w", encoding="utf-8", newline="") as fh: fh.write(content) fh.flush() os.fsync(fh.fileno()) os.chmod(tmp, original_stat.st_mode & 0o7777) os.chown(tmp, original_stat.st_uid, original_stat.st_gid) os.replace(tmp, path) dir_fd = os.open(path.parent, os.O_DIRECTORY) try: os.fsync(dir_fd) finally: os.close(dir_fd) finally: if tmp.exists(): tmp.unlink(missing_ok=True) def create_backup(path: Path, old_text: str) -> Path: BACKUP_DIR.mkdir(parents=True, exist_ok=True) stamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f") backup = BACKUP_DIR / f"{path.name}.{stamp}.bak" with backup.open("w", encoding="utf-8", newline="") as fh: fh.write(old_text) st = path.stat() os.chmod(backup, st.st_mode & 0o7777) prefix = f"{path.name}." backups = sorted( [p for p in BACKUP_DIR.iterdir() if p.name.startswith(prefix) and p.name.endswith(".bak")], key=lambda p: p.stat().st_mtime, reverse=True, ) for stale in backups[MAX_BACKUPS:]: stale.unlink(missing_ok=True) return backup def apply_transaction( path: Path, expected_old_text: str, new_text: str, validate_cmd: list[str], apply_cmd: list[str], ) -> tuple[bool, str]: with CHANGE_LOCK: old_text = read_text_exact(path) if old_text != expected_old_text: return False, "Config file changed since the page action started; nothing was written. Reload the page and try again." if old_text == new_text: return True, "No changes were necessary." # Hard safety boundary: content outside the managed markers must be # exactly identical before a write is allowed. old_prefix, _, old_suffix, _ = split_managed_section(old_text) new_prefix, _, new_suffix, _ = split_managed_section(new_text) if old_prefix != new_prefix or old_suffix != new_suffix: return False, "Safety check failed: text outside the markers changed; nothing was written." stat = path.stat() backup = create_backup(path, old_text) atomic_write(path, new_text, stat) valid, validation_output = run_cmd(validate_cmd) if not valid: atomic_write(path, old_text, stat) return ( False, "Validation failed; original file restored.\n" f"Validator output:\n{validation_output}", ) applied, apply_output = run_cmd(apply_cmd) if applied: return True, f"Applied successfully. Backup: {backup}" # The file was valid, but service action failed. Restore the original # config and make a best-effort attempt to reactivate it. atomic_write(path, old_text, stat) rollback_valid, rollback_validation = run_cmd(validate_cmd) rollback_applied, rollback_apply = run_cmd(apply_cmd) if rollback_valid else (False, "rollback validation failed") details = [ "Service reload/restart failed; original file restored.", f"Apply output: {apply_output}", f"Rollback validation: {rollback_validation}", f"Rollback apply: {rollback_apply}", ] if not rollback_applied: details.append("WARNING: automatic rollback activation also failed; check the service immediately.") return False, "\n".join(details) # ----------------------------------------------------------------------------- # Auth / CSRF # ----------------------------------------------------------------------------- def _auth_ok() -> bool: auth = request.authorization if not auth: return False return hmac.compare_digest(auth.username or "", ADMIN_USER) and hmac.compare_digest( auth.password or "", ADMIN_PASSWORD ) @app.before_request def require_auth(): if AUTH_ENABLED and not _auth_ok(): return ( "Authentication required", 401, {"WWW-Authenticate": 'Basic realm="Proxy Config"'}, ) def csrf_token() -> str: token = session.get("csrf_token") if not token: token = secrets.token_urlsafe(32) session["csrf_token"] = token return token app.jinja_env.globals["csrf_token"] = csrf_token def require_csrf() -> None: expected = session.get("csrf_token", "") supplied = request.form.get("csrf_token", "") if not expected or not hmac.compare_digest(expected, supplied): abort(400, "Invalid CSRF token") # ----------------------------------------------------------------------------- # Routes # ----------------------------------------------------------------------------- def load_state(): caddy_text = read_text_exact(CADDYFILE) dns_text = read_text_exact(DNSMASQ_CONF) caddy_records = parse_caddy_records(get_managed_lines(caddy_text)) dns_records = parse_dns_records(get_managed_lines(dns_text)) caddy_status, caddy_status_text = run_cmd(CADDY_VALIDATE_CMD) dns_status, dns_status_text = run_cmd(DNSMASQ_VALIDATE_CMD) return caddy_records, dns_records, caddy_status, caddy_status_text, dns_status, dns_status_text @app.get("/") def index(): try: state = load_state() except Exception as exc: state = ([], [], False, f"Cannot read Caddy config: {exc}", False, f"Cannot read dnsmasq config: {exc}") return render_template_string( TEMPLATE, caddy_records=state[0], dns_records=state[1], caddy_ok=state[2], caddy_status=state[3], dns_ok=state[4], dns_status=state[5], lan_networks=", ".join(LAN_NETWORKS), dns_target_ip=DNSMASQ_TARGET_IP, auth_enabled=AUTH_ENABLED, ) @app.post("/caddy/add") def caddy_add(): require_csrf() try: site = validate_site(request.form.get("site", "")) upstream = validate_upstream(request.form.get("upstream", "")) comment = validate_comment(request.form.get("comment", "")) lan_only = request.form.get("lan_only") == "on" old = read_text_exact(CADDYFILE) managed = get_managed_lines(old) records = parse_caddy_records(managed) existing_sites = {r.site.strip().lower() for r in records} if site.lower() in existing_sites: raise ValueError(f"Caddy entry for {site} already exists in the managed section.") new_block = build_caddy_block(site, upstream, comment, lan_only) if managed and managed[-1].strip(): managed.append("") managed.extend(new_block) new = replace_managed_lines(old, managed) ok, message = apply_transaction(CADDYFILE, old, new, CADDY_VALIDATE_CMD, CADDY_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/caddy/delete") def caddy_delete(): require_csrf() record_id = request.form.get("record_id", "") try: old = read_text_exact(CADDYFILE) managed = get_managed_lines(old) records = parse_caddy_records(managed) record = next((r for r in records if r.record_id == record_id), None) if record is None: raise ValueError("Caddy record not found; reload the page and try again.") del managed[record.start : record.end + 1] # Collapse excessive blank lines around the removed block. compact: list[str] = [] for line in managed: if line.strip() == "" and compact and compact[-1].strip() == "": continue compact.append(line) while compact and compact[0].strip() == "": compact.pop(0) while compact and compact[-1].strip() == "": compact.pop() new = replace_managed_lines(old, compact) ok, message = apply_transaction(CADDYFILE, old, new, CADDY_VALIDATE_CMD, CADDY_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/dns/add") def dns_add(): require_csrf() try: domain = validate_dns_domain(request.form.get("domain", "")) ip = DNSMASQ_TARGET_IP old = read_text_exact(DNSMASQ_CONF) managed = get_managed_lines(old) records = parse_dns_records(managed) address_domains = {r.domain.lower() for r in records} local_domains = set(parse_dns_local_indices(managed)) key = domain.lower() lines_to_add: list[str] = [] if key not in address_domains: lines_to_add.append(f"address=/{domain}/{ip}") if key not in local_domains: lines_to_add.append(f"local=/{domain}/") if not lines_to_add: raise ValueError( f"dnsmasq entry for {domain} already exists and IPv6 blocking is already enabled." ) append_dns_lines(managed, lines_to_add) new = replace_managed_lines(old, managed) ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD) if ok and len(lines_to_add) == 1: message = f"Запись {domain} приведена к новой схеме address + local.\n{message}" flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/dns/delete") def dns_delete(): require_csrf() record_id = request.form.get("record_id", "") try: old = read_text_exact(DNSMASQ_CONF) managed = get_managed_lines(old) records = parse_dns_records(managed) record = next((r for r in records if r.record_id == record_id), None) if record is None: raise ValueError("dnsmasq record not found; reload the page and try again.") # A domain is one logical record. Remove every managed address/local line # for that exact domain so an orphaned IPv4 redirect or local rule cannot remain. key = record.domain.lower() filtered: list[str] = [] for line in managed: address_match = DNS_ADDRESS_RE.match(line) local_match = DNS_LOCAL_RE.match(line) if address_match and address_match.group(1).lower() == key: continue if local_match and local_match.group(1).lower() == key: continue filtered.append(line) new = replace_managed_lines(old, filtered) ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.post("/dns/import") def dns_import(): require_csrf() try: upload = request.files.get("file") if upload is None or not upload.filename: raise ValueError("Выберите текстовый файл со списком доменов.") data = upload.stream.read(MAX_IMPORT_BYTES + 1) if len(data) > MAX_IMPORT_BYTES: raise ValueError(f"Файл слишком большой. Максимальный размер: {MAX_IMPORT_BYTES} байт.") try: imported_text = data.decode("utf-8-sig") except UnicodeDecodeError as exc: raise ValueError("Файл импорта должен быть в кодировке UTF-8.") from exc domains: list[str] = [] seen_import: set[str] = set() errors: list[str] = [] for lineno, raw_line in enumerate(imported_text.splitlines(), start=1): line = raw_line.strip() if not line or line.startswith("#"): continue try: domain = validate_dns_domain(line) except ValueError: errors.append(f"строка {lineno}: {line}") continue key = domain.lower() if key not in seen_import: seen_import.add(key) domains.append(domain) if errors: preview = "; ".join(errors[:8]) if len(errors) > 8: preview += f"; ещё {len(errors) - 8}" raise ValueError(f"В файле есть некорректные домены: {preview}") if not domains: raise ValueError("В файле не найдено ни одного домена.") old = read_text_exact(DNSMASQ_CONF) managed = get_managed_lines(old) records = parse_dns_records(managed) address_domains = {r.domain.lower() for r in records} local_domains = set(parse_dns_local_indices(managed)) added = 0 repaired = 0 skipped = 0 for domain in domains: key = domain.lower() missing_address = key not in address_domains missing_local = key not in local_domains if not missing_address and not missing_local: skipped += 1 continue lines_to_add: list[str] = [] if missing_address: lines_to_add.append(f"address=/{domain}/{DNSMASQ_TARGET_IP}") address_domains.add(key) if missing_local: lines_to_add.append(f"local=/{domain}/") local_domains.add(key) append_dns_lines(managed, lines_to_add) if missing_address and missing_local: added += 1 else: repaired += 1 if not added and not repaired: flash(f"Изменений нет. Полностью существующих доменов: {skipped}.", "success") return redirect(url_for("index")) new = replace_managed_lines(old, managed) ok, message = apply_transaction(DNSMASQ_CONF, old, new, DNSMASQ_VALIDATE_CMD, DNSMASQ_APPLY_CMD) if ok: message = ( f"Импорт завершён: новых доменов {added}, дополнено до address + local {repaired}, " f"без изменений {skipped}.\n{message}" ) flash(message, "success" if ok else "error") except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.get("/dns/export") def dns_export(): try: text = read_text_exact(DNSMASQ_CONF) records = parse_dns_records(get_managed_lines(text)) content = "\n".join(r.domain for r in records) if content: content += "\n" return Response( content, mimetype="text/plain; charset=utf-8", headers={"Content-Disposition": "attachment; filename=dnsmasq-sites.txt"}, ) except Exception as exc: flash(str(exc), "error") return redirect(url_for("index")) @app.get("/health") def health(): return {"ok": True} # ----------------------------------------------------------------------------- # UI # ----------------------------------------------------------------------------- TEMPLATE = r""" Proxy Config

Proxy Config

Управляемые секции Caddy и dnsmasq. Перед применением конфигурация проверяется, при ошибке выполняется откат.
Авторизация: {{ 'включена' if auth_enabled else 'отключена' }}.
{% with messages = get_flashed_messages(with_categories=true) %} {% for category, message in messages %}
{{ message }}
{% endfor %} {% endwith %}

Caddy

{{ 'конфигурация OK' if caddy_ok else 'ошибка конфигурации' }}
{% for r in caddy_records %} {% else %}{% endfor %}
HostUpstream
{{ r.site }}{% if r.comment %}
{{ r.comment }}
{% endif %}{% if r.lan_only %}LAN only{% endif %}
{{ r.target }}
Записей не найдено.
Результат caddy validate
{{ caddy_status }}

dnsmasq

{{ 'конфигурация OK' if dns_ok else 'ошибка конфигурации' }}
Для каждого домена создаются две строки: address → {{ dns_target_ip }} и local для блокировки внешнего IPv6.

Экспортировать список доменов

{% for r in dns_records %} {% else %}{% endfor %}
DomainIPv4IPv6
{{ r.domain }} {{ r.ip }} {% if r.ipv6_blocked %}заблокирован{% else %}нет local={% endif %}
Записей не найдено.
Результат dnsmasq --test
{{ dns_status }}
""" if __name__ == "__main__": # For manual testing only. The systemd unit uses gunicorn. app.run(host="127.0.0.1", port=8090, debug=False)