work : добавил функционал чтобы для каждой записи dnsmasq создавалась вторая запись local=/address/ для блокировки ipv6
This commit is contained in:
@@ -105,7 +105,9 @@ class DnsRecord:
|
||||
record_id: str
|
||||
domain: str
|
||||
ip: str
|
||||
index: int
|
||||
address_index: int
|
||||
local_indices: tuple[int, ...]
|
||||
ipv6_blocked: bool
|
||||
raw: str
|
||||
|
||||
|
||||
@@ -266,25 +268,51 @@ def parse_caddy_records(managed: list[str]) -> list[CaddyRecord]:
|
||||
return records
|
||||
|
||||
|
||||
def parse_dns_records(managed: list[str]) -> list[DnsRecord]:
|
||||
records: list[DnsRecord] = []
|
||||
rx = re.compile(r"^\s*address=/([^/]+)/([^/\s]+)\s*$")
|
||||
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 = rx.match(line)
|
||||
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=m.group(1),
|
||||
domain=domain,
|
||||
ip=m.group(2),
|
||||
index=idx,
|
||||
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
|
||||
# -----------------------------------------------------------------------------
|
||||
@@ -647,16 +675,26 @@ def dns_add():
|
||||
old = read_text_exact(DNSMASQ_CONF)
|
||||
managed = get_managed_lines(old)
|
||||
records = parse_dns_records(managed)
|
||||
if domain.lower() in {r.domain.lower() for r in records}:
|
||||
raise ValueError(f"dnsmasq entry for {domain} already exists in the managed section.")
|
||||
address_domains = {r.domain.lower() for r in records}
|
||||
local_domains = set(parse_dns_local_indices(managed))
|
||||
key = domain.lower()
|
||||
|
||||
if managed and managed[-1].strip() == "":
|
||||
managed[-1] = f"address=/{domain}/{ip}"
|
||||
else:
|
||||
managed.append(f"address=/{domain}/{ip}")
|
||||
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")
|
||||
@@ -674,8 +712,21 @@ def dns_delete():
|
||||
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.")
|
||||
del managed[record.index]
|
||||
new = replace_managed_lines(old, managed)
|
||||
|
||||
# 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:
|
||||
@@ -728,26 +779,46 @@ def dns_import():
|
||||
old = read_text_exact(DNSMASQ_CONF)
|
||||
managed = get_managed_lines(old)
|
||||
records = parse_dns_records(managed)
|
||||
existing = {r.domain.lower() for r in records}
|
||||
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:
|
||||
if domain.lower() in existing:
|
||||
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
|
||||
managed.append(f"address=/{domain}/{DNSMASQ_TARGET_IP}")
|
||||
existing.add(domain.lower())
|
||||
added += 1
|
||||
|
||||
if not added:
|
||||
flash(f"Новых доменов нет. Пропущено существующих: {skipped}.", "success")
|
||||
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}, пропущено существующих {skipped}.\n{message}"
|
||||
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")
|
||||
@@ -882,7 +953,7 @@ TEMPLATE = r"""
|
||||
<form class="add" method="post" action="{{ url_for('dns_add') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label class="wide">Домен<input type="text" name="domain" required placeholder="example.com или .example.com"></label>
|
||||
<div class="wide muted">Все новые записи направляются на {{ dns_target_ip }}.</div>
|
||||
<div class="wide muted">Для каждого домена создаются две строки: address → {{ dns_target_ip }} и local для блокировки внешнего IPv6.</div>
|
||||
<button class="wide" type="submit">Добавить DNS-запись</button>
|
||||
</form>
|
||||
|
||||
@@ -894,12 +965,13 @@ TEMPLATE = r"""
|
||||
<p><a class="button-link" href="{{ url_for('dns_export') }}">Экспортировать список доменов</a></p>
|
||||
|
||||
<table>
|
||||
<thead><tr><th>Domain</th><th>IP</th><th></th></tr></thead>
|
||||
<thead><tr><th>Domain</th><th>IPv4</th><th>IPv6</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in dns_records %}
|
||||
<tr>
|
||||
<td><strong>{{ r.domain }}</strong></td>
|
||||
<td><code>{{ r.ip }}</code></td>
|
||||
<td>{% if r.ipv6_blocked %}<span class="tag">заблокирован</span>{% else %}<span class="muted">нет local=</span>{% endif %}</td>
|
||||
<td>
|
||||
<form method="post" action="{{ url_for('dns_delete') }}" onsubmit="return confirm('Удалить {{ r.domain }}?')">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
@@ -908,7 +980,7 @@ TEMPLATE = r"""
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}<tr><td colspan="3" class="muted">Записей не найдено.</td></tr>{% endfor %}
|
||||
{% else %}<tr><td colspan="4" class="muted">Записей не найдено.</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
<details><summary>Результат dnsmasq --test</summary><pre>{{ dns_status }}</pre></details>
|
||||
|
||||
Reference in New Issue
Block a user