linuxrouter/docker/routlin-dash/app/pages/networklayout/action.py
2026-06-05 01:48:27 -04:00

366 lines
14 KiB
Python

from pathlib import Path
import copy
import ipaddress
import json
from flask import Blueprint, request, redirect, flash
from auth import require_level
from config_utils import load_config, record_group, diff_fields, verify_config_hash
import sanitize
import mod_validation as validate
_PAGE = Path(__file__).parent.name
bp = Blueprint(_PAGE, __name__)
def _row_index():
try:
return int(request.form.get('row_index', ''))
except (ValueError, TypeError):
return None
def _hash_ok():
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return False
return True
@bp.route('/action/networklayout/vlans_addedit', methods=['POST'])
@require_level('administrator')
def vlans_addedit():
_ri = request.form.get('row_index', '').strip()
try:
edit_idx = int(_ri)
is_edit = True
except (ValueError, TypeError):
edit_idx = None
is_edit = False
name = sanitize.name(request.form.get('name', ''))
vlan_id = sanitize.vlan_id(request.form.get('vlan_id', ''))
subnet = sanitize.ip(request.form.get('subnet', ''))
subnet_mask = sanitize.subnet_mask(request.form.get('subnet_mask', ''))
radius_default = 'radius_default' in request.form
mdns_reflection = 'mdns_reflection' in request.form
dnsmasq_log_queries = 'dnsmasq_log_queries' in request.form
use_blocklists = sanitize.filterlist(
request.form.getlist('use_blocklists'),
{b.get('name') for b in load_config().get('dns_blocking', {}).get('blocklists', [])},
)
if not name:
flash('Name is required.', 'error')
return redirect(f'/{_PAGE}')
if vlan_id is None:
flash('VLAN ID must be an integer between 1 and 4094.', 'error')
return redirect(f'/{_PAGE}')
if not subnet:
flash('Subnet IP is required.', 'error')
return redirect(f'/{_PAGE}')
if subnet_mask is None:
flash('Invalid subnet prefix (must be 1-30).', 'error')
return redirect(f'/{_PAGE}')
_vlan_net = ipaddress.IPv4Network(f'{subnet}/{subnet_mask}', strict=False)
if ipaddress.IPv4Address(subnet) != _vlan_net.network_address:
flash(f"Subnet IP must be a network address (expected {_vlan_net.network_address}).", 'error')
return redirect(f'/{_PAGE}')
if not _hash_ok():
return redirect(f'/{_PAGE}')
server_identities_raw = request.form.get('server_identities', '[]')
try:
raw_identities = json.loads(server_identities_raw)
if not isinstance(raw_identities, list):
raise ValueError
except (ValueError, TypeError):
flash('Invalid identity data.', 'error')
return redirect(f'/{_PAGE}')
new_identities = []
for raw in raw_identities:
ip_clean = sanitize.ip(str(raw.get('ip', '')))
if not ip_clean:
flash('Invalid IP address in identity.', 'error')
return redirect(f'/{_PAGE}')
_addr = ipaddress.IPv4Address(ip_clean)
if _addr not in _vlan_net:
flash(f"Identity IP '{ip_clean}' is not in the VLAN subnet ({subnet}/{subnet_mask}).", 'error')
return redirect(f'/{_PAGE}')
if _addr == _vlan_net.network_address or _addr == _vlan_net.broadcast_address:
flash(f"Identity IP '{ip_clean}' cannot be the network or broadcast address.", 'error')
return redirect(f'/{_PAGE}')
ident = {'ip': ip_clean}
desc = str(raw.get('description', '')).strip()
if desc:
ident['description'] = desc
hostname_raw = str(raw.get('hostname', '')).strip()
if hostname_raw:
clean_hostname = sanitize.hostname(hostname_raw)
if clean_hostname is None:
flash(f"'{hostname_raw}' is not a valid hostname.", 'error')
return redirect(f'/{_PAGE}')
ident['hostname'] = clean_hostname
new_identities.append(ident)
identity_ips = [ident['ip'] for ident in new_identities]
gateway_raw = sanitize.ip(request.form.get('gateway', ''))
if gateway_raw and gateway_raw not in identity_ips:
flash(f"Gateway '{gateway_raw}' must match one of the server identity IPs.", 'error')
return redirect(f'/{_PAGE}')
inferred_gw = (min(identity_ips, key=lambda ip: int(ip.split('.')[-1])) if identity_ips else '')
new_stored_gw = gateway_raw if (gateway_raw and gateway_raw != inferred_gw) else ''
dns_override = 'dns_servers_override' in request.form
dns_ips = []
for _line in request.form.get('dns_servers', '').splitlines():
_line = _line.strip()
if not _line:
continue
_clean = sanitize.ip(_line)
if not _clean:
flash(f"'{_line}' is not a valid DNS server IP.", 'error')
return redirect(f'/{_PAGE}')
dns_ips.append(_clean)
if dns_override and dns_ips:
for _ip in dns_ips:
if ipaddress.IPv4Address(_ip) not in _vlan_net:
flash(f"DNS server '{_ip}' is not in the VLAN subnet ({subnet}/{subnet_mask}).", 'error')
return redirect(f'/{_PAGE}')
new_stored_dns = dns_ips if dns_override else []
ntp_override = 'ntp_servers_override' in request.form
ntp_ips = []
for _line in request.form.get('ntp_servers', '').splitlines():
_line = _line.strip()
if not _line:
continue
_clean = sanitize.ip(_line)
if not _clean:
flash(f"'{_line}' is not a valid NTP server IP.", 'error')
return redirect(f'/{_PAGE}')
ntp_ips.append(_clean)
if ntp_override and ntp_ips:
for _ip in ntp_ips:
if ipaddress.IPv4Address(_ip) not in _vlan_net:
flash(f"NTP server '{_ip}' is not in the VLAN subnet ({subnet}/{subnet_mask}).", 'error')
return redirect(f'/{_PAGE}')
new_stored_ntp = ntp_ips if ntp_override else []
dhcp_domain_raw = request.form.get('dhcp_domain', '').strip()
dhcp_domain = sanitize.hostname(dhcp_domain_raw) if dhcp_domain_raw else 'local'
if dhcp_domain_raw and dhcp_domain is None:
flash(f"'{dhcp_domain_raw}' is not a valid domain name.", 'error')
return redirect(f'/{_PAGE}')
dhcp_pool_start = sanitize.ip(request.form.get('dhcp_pool_start', ''))
dhcp_pool_end = sanitize.ip(request.form.get('dhcp_pool_end', ''))
if dhcp_pool_start and ipaddress.IPv4Address(dhcp_pool_start) not in _vlan_net:
flash(f"Pool start '{dhcp_pool_start}' is not in the VLAN subnet ({subnet}/{subnet_mask}).", 'error')
return redirect(f'/{_PAGE}')
if dhcp_pool_end and ipaddress.IPv4Address(dhcp_pool_end) not in _vlan_net:
flash(f"Pool end '{dhcp_pool_end}' is not in the VLAN subnet ({subnet}/{subnet_mask}).", 'error')
return redirect(f'/{_PAGE}')
if dhcp_pool_start and dhcp_pool_end:
if ipaddress.IPv4Address(dhcp_pool_start) > ipaddress.IPv4Address(dhcp_pool_end):
flash('Pool start must not be greater than pool end.', 'error')
return redirect(f'/{_PAGE}')
_lease_time_raw = request.form.get('dhcp_lease_time', '').strip()
_lease_unit_raw = request.form.get('dhcp_lease_unit', '').strip()
dhcp_lease_time = None
if _lease_time_raw:
try:
_lt = int(_lease_time_raw)
if _lt < 1:
raise ValueError
except ValueError:
flash('Lease time must be a positive integer.', 'error')
return redirect(f'/{_PAGE}')
_unit_suffix = {'minutes': 'm', 'hours': 'h', 'days': 'd'}.get(_lease_unit_raw)
if not _unit_suffix:
flash('Lease time unit must be minutes, hours, or days.', 'error')
return redirect(f'/{_PAGE}')
dhcp_lease_time = f'{_lt}{_unit_suffix}'
dhcp_info = {}
if dhcp_domain and dhcp_domain != 'local':
dhcp_info['domain'] = dhcp_domain
if dhcp_pool_start:
dhcp_info['dynamic_pool_start'] = dhcp_pool_start
if dhcp_pool_end:
dhcp_info['dynamic_pool_end'] = dhcp_pool_end
if dhcp_lease_time:
dhcp_info['lease_time'] = dhcp_lease_time
dhcp_overrides = {}
if new_stored_gw:
dhcp_overrides['gateway'] = new_stored_gw
if new_stored_dns:
dhcp_overrides['dns_servers'] = new_stored_dns
if new_stored_ntp:
dhcp_overrides['ntp_servers'] = new_stored_ntp
if dhcp_overrides:
dhcp_info['explicit_overrides'] = dhcp_overrides
cfg = load_config()
vlans = cfg.setdefault('vlans', [])
if is_edit:
if edit_idx < 0 or edit_idx >= len(vlans):
flash('VLAN not found.', 'error')
return redirect(f'/{_PAGE}')
existing = vlans[edit_idx]
is_vpn = existing.get('is_vpn', False)
# VPN VLANs do not support mDNS reflection
err = validate.check_mdns_vpn(is_vpn, mdns_reflection)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
# VLAN 1 maps to the physical LAN interface; its ID is fixed
current_id = existing.get('vlan_id')
if current_id == 1 and vlan_id != 1:
flash('VLAN 1 is the physical interface and cannot change its ID.', 'error')
return redirect(f'/{_PAGE}')
# VLAN ID must be unique across all VLANs (used as 802.1Q tag and interface name)
err = validate.check_vlan_id_unique(vlans, vlan_id, exclude_idx=edit_idx)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
# VLAN name must be unique - it is used as the change-history lookup key
err = validate.check_vlan_name_unique(vlans, name, exclude_idx=edit_idx)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
# Only one VLAN may be the RADIUS default (used for dynamic VLAN assignment)
if radius_default:
err = validate.check_radius_default_unique(vlans, exclude_idx=edit_idx)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
before = copy.deepcopy(existing)
existing.update({
'name': name,
'vlan_id': vlan_id,
'subnet': subnet,
'subnet_mask': subnet_mask,
'dnsmasq_log_queries': dnsmasq_log_queries,
'radius_default': radius_default,
'mdns_reflection': mdns_reflection,
'use_blocklists': use_blocklists,
'server_identities': new_identities,
})
if dhcp_info:
existing['dhcp_information'] = dhcp_info
else:
existing.pop('dhcp_information', None)
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(f'/{_PAGE}')
changes = diff_fields(before, existing)
if not changes:
flash('No changes were made.', 'info')
return redirect(f'/{_PAGE}')
flash(record_group(cfg, 'vlans', 'name', name, changes, 'core apply'), 'success')
else:
is_vpn = 'is_vpn' in request.form
# VPN VLANs do not support mDNS reflection
err = validate.check_mdns_vpn(is_vpn, mdns_reflection)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
# VLAN ID must be unique across all VLANs (used as 802.1Q tag and interface name)
err = validate.check_vlan_id_unique(vlans, vlan_id)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
# VLAN name must be unique - it is used as the change-history lookup key
err = validate.check_vlan_name_unique(vlans, name)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
# Only one VLAN may be the RADIUS default (used for dynamic VLAN assignment)
if radius_default:
err = validate.check_radius_default_unique(vlans)
if err:
flash(err, 'error')
return redirect(f'/{_PAGE}')
entry = {
'name': name,
'vlan_id': vlan_id,
'is_vpn': is_vpn,
'subnet': subnet,
'subnet_mask': subnet_mask,
'dnsmasq_log_queries': dnsmasq_log_queries,
'use_blocklists': use_blocklists,
'radius_default': radius_default,
'mdns_reflection': mdns_reflection,
'server_identities': new_identities,
}
if dhcp_info:
entry['dhcp_information'] = dhcp_info
if is_vpn:
entry['peers'] = []
else:
entry['reservations'] = []
vlans.append(entry)
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(f'/{_PAGE}')
changes = diff_fields(None, entry)
flash(record_group(cfg, 'vlans', 'name', name, changes, 'core apply'), 'success')
return redirect(f'/{_PAGE}')
@bp.route('/action/networklayout/vlans_delete', methods=['POST'])
@require_level('administrator')
def vlans_delete():
idx = _row_index()
if idx is None:
flash('Invalid request.', 'error')
return redirect(f'/{_PAGE}')
if not _hash_ok():
return redirect(f'/{_PAGE}')
cfg = load_config()
vlans = cfg.get('vlans', [])
if idx < 0 or idx >= len(vlans):
flash('VLAN not found.', 'error')
return redirect(f'/{_PAGE}')
removed = vlans.pop(idx)
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(f'/{_PAGE}')
changes = diff_fields(removed, None)
flash(record_group(cfg, 'vlans', 'name', removed['name'], changes, 'core apply'), 'success')
return redirect(f'/{_PAGE}')