APmanageur Wi-Fi V1.0
This commit is contained in:
1 parent
043cab7d7a
commit
89a14cbe89
3 files changed
+263
-61
No files matched your search
+1
-1
@@ -7,7 +7,7 @@ ENV DEBIAN_FRONTEND=noninteractive \
|
|||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt full-upgrade -y && apt-get install -y --no-install-recommends \
|
&& apt full-upgrade -y && apt-get install -y --no-install-recommends \
|
||||||
ca-certificates apache2 nano python3 python3-cryptography tzdata \
|
ca-certificates apache2 nano python3 python3-cryptography tzdata \
|
||||||
network-manager wpasupplicant dbus \
|
network-manager wpasupplicant hostapd dbus \
|
||||||
iw iproute2 rfkill wireless-regdb \
|
iw iproute2 rfkill wireless-regdb \
|
||||||
dnsmasq-base iptables nftables procps kmod tcpdump \
|
dnsmasq-base iptables nftables procps kmod tcpdump \
|
||||||
wireguard-tools openvpn ebtables curl conntrack \
|
wireguard-tools openvpn ebtables curl conntrack \
|
||||||
|
|||||||
@@ -1426,6 +1426,7 @@ def save_connection(name):
|
|||||||
|
|
||||||
def apply_radio_defaults():
|
def apply_radio_defaults():
|
||||||
"""Applique bande/canal/CCMP à la connexion AP déjà créée (sans avoir à ré-enregistrer les réglages)."""
|
"""Applique bande/canal/CCMP à la connexion AP déjà créée (sans avoir à ré-enregistrer les réglages)."""
|
||||||
|
if is_bridge_mode(): return
|
||||||
name = connection_name()
|
name = connection_name()
|
||||||
if not name: return
|
if not name: return
|
||||||
band = command('nmcli','-t','-g','802-11-wireless.band','connection','show',name)
|
band = command('nmcli','-t','-g','802-11-wireless.band','connection','show',name)
|
||||||
@@ -2937,6 +2938,189 @@ def teardown_ap_nat():
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
HOSTAPD_CONF_FILE = '/run/ap-hostapd.conf'
|
||||||
|
HOSTAPD_PID_FILE = '/run/ap-hostapd.pid'
|
||||||
|
HOSTAPD_LOG_FILE = '/run/ap-hostapd.log'
|
||||||
|
|
||||||
|
def is_hostapd_running():
|
||||||
|
"""Retourne True si l'instance hostapd (mode pont) est en cours d'exécution."""
|
||||||
|
try:
|
||||||
|
if os.path.exists(HOSTAPD_PID_FILE):
|
||||||
|
pid = int(open(HOSTAPD_PID_FILE).read().strip())
|
||||||
|
os.kill(pid, 0)
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
r = subprocess.run(['pgrep', '-f', HOSTAPD_CONF_FILE], capture_output=True, text=True)
|
||||||
|
return r.returncode == 0 and bool(r.stdout.strip())
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def stop_hostapd(iface=None):
|
||||||
|
"""Arrête proprement hostapd et détache l'interface Wi-Fi du pont sans jamais toucher au pont hôte."""
|
||||||
|
iface = iface or INTERFACE
|
||||||
|
try:
|
||||||
|
if os.path.exists(HOSTAPD_PID_FILE):
|
||||||
|
try:
|
||||||
|
pid = int(open(HOSTAPD_PID_FILE).read().strip())
|
||||||
|
os.kill(pid, signal.SIGTERM)
|
||||||
|
for _ in range(15):
|
||||||
|
try:
|
||||||
|
os.kill(pid, 0)
|
||||||
|
time.sleep(0.1)
|
||||||
|
except OSError:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
os.kill(pid, signal.SIGKILL)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try: os.remove(HOSTAPD_PID_FILE)
|
||||||
|
except OSError: pass
|
||||||
|
subprocess.run(['pkill', '-f', HOSTAPD_CONF_FILE], capture_output=True)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if iface:
|
||||||
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
|
||||||
|
|
||||||
|
def ensure_nm_manages_wifi(iface=None):
|
||||||
|
"""Rend le contrôle de l'interface Wi-Fi à NetworkManager (pour le mode AP/NAT)."""
|
||||||
|
iface = iface or INTERFACE
|
||||||
|
if not iface:
|
||||||
|
return
|
||||||
|
stop_hostapd(iface)
|
||||||
|
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'yes'], capture_output=True)
|
||||||
|
for _ in range(25):
|
||||||
|
st = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', iface)
|
||||||
|
if st and not st.startswith('10'): # 10 = unmanaged
|
||||||
|
break
|
||||||
|
time.sleep(0.2)
|
||||||
|
|
||||||
|
def start_bridge_hostapd(ssid, password, sec='wpa2', bridge_name='br0', iface=None):
|
||||||
|
"""Démarre le point d'accès Wi-Fi en mode pont directement via hostapd (bridge=br0) sans que NetworkManager ne touche au pont hôte."""
|
||||||
|
iface = iface or INTERFACE
|
||||||
|
bridge_name = bridge_name or 'br0'
|
||||||
|
hostapd_bin = find_bin('hostapd')
|
||||||
|
if not hostapd_bin:
|
||||||
|
raise RuntimeError("Le binaire 'hostapd' est introuvable dans le conteneur. Veuillez reconstruire l'image Docker.")
|
||||||
|
if not os.path.exists(f'/sys/class/net/{bridge_name}'):
|
||||||
|
raise RuntimeError(f"Le pont réseau '{bridge_name}' n'existe pas sur le système.")
|
||||||
|
|
||||||
|
# 1. Arrêter toute ancienne instance hostapd et retirer le contrôle NM de la carte Wi-Fi uniquement
|
||||||
|
stop_hostapd(iface)
|
||||||
|
subprocess.run(['nmcli', 'device', 'disconnect', iface], capture_output=True)
|
||||||
|
subprocess.run(['nmcli', 'device', 'set', iface, 'managed', 'no'], capture_output=True)
|
||||||
|
time.sleep(0.4)
|
||||||
|
subprocess.run(['rfkill', 'unblock', 'wifi'], capture_output=True)
|
||||||
|
subprocess.run(['ip', 'addr', 'flush', 'dev', iface], capture_output=True)
|
||||||
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'nomaster'], capture_output=True)
|
||||||
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'up'], capture_output=True)
|
||||||
|
|
||||||
|
country = os.environ.get('AP_COUNTRY', 'FR').strip().upper() or 'FR'
|
||||||
|
band = (AP_BAND or 'bg').strip().lower()
|
||||||
|
hw_mode = 'a' if band == 'a' else 'g'
|
||||||
|
channel = str(AP_CHANNEL or '6').strip()
|
||||||
|
sec_norm = (sec or 'wpa2').lower()
|
||||||
|
|
||||||
|
def _build_conf(enable_ht=True):
|
||||||
|
lines = [
|
||||||
|
f"interface={iface}",
|
||||||
|
f"bridge={bridge_name}",
|
||||||
|
"driver=nl80211",
|
||||||
|
f"ssid={ssid}",
|
||||||
|
"utf8_ssid=1",
|
||||||
|
f"country_code={country}",
|
||||||
|
"ieee80211d=1",
|
||||||
|
f"hw_mode={hw_mode}",
|
||||||
|
f"channel={channel}",
|
||||||
|
"auth_algs=1",
|
||||||
|
"ignore_broadcast_ssid=0",
|
||||||
|
"wmm_enabled=1",
|
||||||
|
"ctrl_interface=/run/hostapd",
|
||||||
|
"ctrl_interface_group=0",
|
||||||
|
]
|
||||||
|
if enable_ht:
|
||||||
|
lines.append("ieee80211n=1")
|
||||||
|
if hw_mode == 'a':
|
||||||
|
lines.append("ieee80211ac=1")
|
||||||
|
if sec_norm == 'wpa1':
|
||||||
|
lines += [
|
||||||
|
"wpa=1",
|
||||||
|
"wpa_key_mgmt=WPA-PSK",
|
||||||
|
"wpa_pairwise=TKIP CCMP",
|
||||||
|
f"wpa_passphrase={password}",
|
||||||
|
]
|
||||||
|
elif sec_norm == 'wpa3':
|
||||||
|
lines += [
|
||||||
|
"wpa=2",
|
||||||
|
"wpa_key_mgmt=SAE",
|
||||||
|
"rsn_pairwise=CCMP",
|
||||||
|
f"sae_password={password}",
|
||||||
|
f"wpa_passphrase={password}",
|
||||||
|
"ieee80211w=2",
|
||||||
|
]
|
||||||
|
else:
|
||||||
|
lines += [
|
||||||
|
"wpa=2",
|
||||||
|
"wpa_key_mgmt=WPA-PSK",
|
||||||
|
"rsn_pairwise=CCMP",
|
||||||
|
f"wpa_passphrase={password}",
|
||||||
|
]
|
||||||
|
return '\n'.join(lines) + '\n'
|
||||||
|
|
||||||
|
os.makedirs('/run/hostapd', exist_ok=True)
|
||||||
|
|
||||||
|
def _try_launch(enable_ht=True):
|
||||||
|
with open(HOSTAPD_CONF_FILE, 'w', encoding='utf-8') as f:
|
||||||
|
f.write(_build_conf(enable_ht=enable_ht))
|
||||||
|
os.chmod(HOSTAPD_CONF_FILE, 0o600)
|
||||||
|
try: os.remove(HOSTAPD_LOG_FILE)
|
||||||
|
except OSError: pass
|
||||||
|
r = subprocess.run(
|
||||||
|
[hostapd_bin, '-B', '-P', HOSTAPD_PID_FILE, '-f', HOSTAPD_LOG_FILE, HOSTAPD_CONF_FILE],
|
||||||
|
capture_output=True, text=True, timeout=15
|
||||||
|
)
|
||||||
|
if r.returncode != 0:
|
||||||
|
err = (r.stderr or r.stdout or '').strip()
|
||||||
|
if os.path.exists(HOSTAPD_LOG_FILE):
|
||||||
|
try:
|
||||||
|
log_tail = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read().strip()
|
||||||
|
if log_tail:
|
||||||
|
last_line = log_tail.splitlines()[-1]
|
||||||
|
err = last_line if not err else f"{err} | {last_line}"
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return False, err or 'hostapd a refusé de démarrer'
|
||||||
|
for _ in range(25):
|
||||||
|
time.sleep(0.2)
|
||||||
|
if is_hostapd_running() and os.path.exists(f'/sys/class/net/{iface}/master'):
|
||||||
|
return True, ''
|
||||||
|
if not is_hostapd_running():
|
||||||
|
break
|
||||||
|
if is_hostapd_running():
|
||||||
|
if not os.path.exists(f'/sys/class/net/{iface}/master'):
|
||||||
|
subprocess.run(['ip', 'link', 'set', 'dev', iface, 'master', bridge_name], capture_output=True)
|
||||||
|
return True, ''
|
||||||
|
err = ''
|
||||||
|
if os.path.exists(HOSTAPD_LOG_FILE):
|
||||||
|
try: err = open(HOSTAPD_LOG_FILE, encoding='utf-8', errors='replace').read().strip()
|
||||||
|
except OSError: pass
|
||||||
|
return False, err or 'hostapd s’est arrêté immédiatement'
|
||||||
|
|
||||||
|
ok, err = _try_launch(enable_ht=True)
|
||||||
|
if not ok:
|
||||||
|
print(f"[ap-bridge] hostapd (802.11n) a échoué ({err}), nouvelle tentative sans 802.11n...", flush=True)
|
||||||
|
stop_hostapd(iface)
|
||||||
|
ok, err2 = _try_launch(enable_ht=False)
|
||||||
|
if not ok:
|
||||||
|
raise RuntimeError(f"Impossible de démarrer le point d'accès en mode Pont (hostapd) : {err2 or err}")
|
||||||
|
|
||||||
|
# Appliquer la redirection DNS du mode pont maintenant que l'AP est actif
|
||||||
|
setup_bridge_dns_redirection(bridge_name, iface)
|
||||||
|
print(f"[ap-bridge] Point d'accès Pont actif via hostapd sur {iface} -> {bridge_name} (SSID='{ssid}', sécurité={sec_norm})", flush=True)
|
||||||
|
|
||||||
def setup_bridge(bridge_name='br0', bridge_eth=None):
|
def setup_bridge(bridge_name='br0', bridge_eth=None):
|
||||||
teardown_ap_nat()
|
teardown_ap_nat()
|
||||||
bridge_name = bridge_name or 'br0'
|
bridge_name = bridge_name or 'br0'
|
||||||
@@ -2985,10 +3169,13 @@ def setup_bridge(bridge_name='br0', bridge_eth=None):
|
|||||||
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
|
subprocess.run(['sysctl', '-w', 'net.ipv4.ip_forward=1'], capture_output=True)
|
||||||
except Exception: pass
|
except Exception: pass
|
||||||
clean_stale_router_leases()
|
clean_stale_router_leases()
|
||||||
subprocess.run(['iptables', '-I', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True)
|
for ipt in _ap_iptables_bins():
|
||||||
|
if subprocess.run([ipt, '-w', '5', '-C', 'FORWARD', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True).returncode != 0:
|
||||||
|
subprocess.run([ipt, '-w', '5', '-I', 'FORWARD', '1', '-i', bridge_name, '-o', bridge_name, '-j', 'ACCEPT'], capture_output=True)
|
||||||
setup_bridge_dns_redirection(bridge_name, INTERFACE)
|
setup_bridge_dns_redirection(bridge_name, INTERFACE)
|
||||||
|
|
||||||
def teardown_bridge(bridge_name='br0', bridge_eth=None):
|
def teardown_bridge(bridge_name='br0', bridge_eth=None):
|
||||||
|
stop_hostapd(INTERFACE)
|
||||||
teardown_bridge_dns_redirection(bridge_name, INTERFACE)
|
teardown_bridge_dns_redirection(bridge_name, INTERFACE)
|
||||||
bridge_name = bridge_name or 'br0'
|
bridge_name = bridge_name or 'br0'
|
||||||
bridge_path = f'/sys/class/net/{bridge_name}'
|
bridge_path = f'/sys/class/net/{bridge_name}'
|
||||||
@@ -3073,11 +3260,15 @@ def status(force_refresh=False):
|
|||||||
sec = 'wpa3' if key == 'sae' else 'wpa1' if proto == 'wpa' else 'wpa2'
|
sec = 'wpa3' if key == 'sae' else 'wpa1' if proto == 'wpa' else 'wpa2'
|
||||||
else:
|
else:
|
||||||
sec = db_sec if db_sec in ('wpa1', 'wpa2', 'wpa3') else 'wpa2'
|
sec = db_sec if db_sec in ('wpa1', 'wpa2', 'wpa3') else 'wpa2'
|
||||||
|
mode = current_mode()
|
||||||
state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE)
|
state = command('nmcli','-t','-g','GENERAL.STATE','device','show',INTERFACE)
|
||||||
# CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté.
|
# CORRECTION : "30 (disconnected)" contient "connected" ; seul le code 100 signifie connecté.
|
||||||
|
if mode == 'bridge':
|
||||||
|
active = is_hostapd_running() or (is_iface_up(INTERFACE) and os.path.exists(f'/sys/class/net/{INTERFACE}/master'))
|
||||||
|
else:
|
||||||
active = state.startswith('100')
|
active = state.startswith('100')
|
||||||
nm_auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name).lower() if name else ''
|
nm_auto = command('nmcli','-t','-g','connection.autoconnect','connection','show',name).lower() if name else ''
|
||||||
if nm_auto in ('yes', 'no'):
|
if nm_auto in ('yes', 'no') and mode != 'bridge':
|
||||||
auto = (nm_auto == 'yes')
|
auto = (nm_auto == 'yes')
|
||||||
elif db_auto is not None:
|
elif db_auto is not None:
|
||||||
auto = str(db_auto).lower() in ('1', 'true', 'yes', 'oui')
|
auto = str(db_auto).lower() in ('1', 'true', 'yes', 'oui')
|
||||||
@@ -3085,9 +3276,10 @@ def status(force_refresh=False):
|
|||||||
auto = False
|
auto = False
|
||||||
if active and uptime_start() is None:
|
if active and uptime_start() is None:
|
||||||
mark_ap_started()
|
mark_ap_started()
|
||||||
slave_type = (command('nmcli','-t','-g','connection.slave-type','connection','show',name) or command('nmcli','-t','-g','connection.port-type','connection','show',name)).lower() if name else ''
|
|
||||||
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name)) if name else ''
|
master = (command('nmcli','-t','-g','connection.master','connection','show',name) or command('nmcli','-t','-g','connection.controller','connection','show',name)) if name else ''
|
||||||
mode = current_mode()
|
if not master and os.path.exists(f'/sys/class/net/{INTERFACE}/master'):
|
||||||
|
try: master = os.path.basename(os.readlink(f'/sys/class/net/{INTERFACE}/master'))
|
||||||
|
except OSError: pass
|
||||||
b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
b_name = master or get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
||||||
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
||||||
res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME}
|
res = {'ssid':ssid or 'SSID inconnu','password':password,'security':sec,'autoconnect':auto,'mode':mode,'bridge_name':b_name,'bridge_eth':b_eth,'ethernet_interfaces':detect_ethernet_interfaces(),'interface':INTERFACE,'connection':name,'active':active,'configured':bool(name or db_ssid),'uptime_seconds':ap_uptime() if active else 0,'max_clients':get_max_clients(),'dns':get_dns_servers(),'is_starting':not app_startup_done,'boot_time':SERVER_BOOT_TIME}
|
||||||
@@ -4525,15 +4717,15 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
|
|||||||
|
|
||||||
print(f"[ap-wifi] Configuration AP: SSID='{ssid}', Sécurité={sec}, Mode={mode}, Autoconnect={'oui' if autoconnect else 'non'}", flush=True)
|
print(f"[ap-wifi] Configuration AP: SSID='{ssid}', Sécurité={sec}, Mode={mode}, Autoconnect={'oui' if autoconnect else 'non'}", flush=True)
|
||||||
|
|
||||||
# Arrêter et supprimer proprement toute ancienne connexion pour éviter les conflits d'options slave/master/ipv4
|
# Arrêter et supprimer proprement toute ancienne connexion NM / instance hostapd pour éviter tout conflit
|
||||||
|
stop_hostapd(INTERFACE)
|
||||||
to_delete = {n for n in (old_name, target_name) if n}
|
to_delete = {n for n in (old_name, target_name) if n}
|
||||||
for c in to_delete:
|
for c in to_delete:
|
||||||
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True, text=True)
|
subprocess.run(['nmcli', 'connection', 'down', c], capture_output=True, text=True)
|
||||||
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True, text=True)
|
subprocess.run(['nmcli', 'connection', 'delete', c], capture_output=True, text=True)
|
||||||
|
|
||||||
if mode == 'bridge':
|
if mode == 'bridge':
|
||||||
if start_now:
|
teardown_ap_nat()
|
||||||
setup_bridge(bridge_name, bridge_eth)
|
|
||||||
# Arrêter le dnsmasq interne pour que les clients reçoivent l'IP de la box et non 10.42.0.x
|
# Arrêter le dnsmasq interne pour que les clients reçoivent l'IP de la box et non 10.42.0.x
|
||||||
subprocess.run(['pkill', '-f', 'dnsmasq.*shared'], text=True, capture_output=True)
|
subprocess.run(['pkill', '-f', 'dnsmasq.*shared'], text=True, capture_output=True)
|
||||||
for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']:
|
for lf in ['/var/lib/misc/dnsmasq.leases', '/var/lib/NetworkManager/dnsmasq.leases']:
|
||||||
@@ -4541,37 +4733,15 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
|
|||||||
if os.path.exists(lf): open(lf, 'w').close()
|
if os.path.exists(lf): open(lf, 'w').close()
|
||||||
except OSError: pass
|
except OSError: pass
|
||||||
|
|
||||||
add_args = [
|
save_connection(name)
|
||||||
'nmcli', 'connection', 'add',
|
if start_now:
|
||||||
'type', 'wifi',
|
# Prépare le pont noyau sans JAMAIS rendre br0 géré par NetworkManager (préserve l'IP et le DNS de l'hôte)
|
||||||
'ifname', INTERFACE,
|
setup_bridge(bridge_name, bridge_eth)
|
||||||
'con-name', name,
|
start_bridge_hostapd(ssid, password, sec=sec, bridge_name=bridge_name, iface=INTERFACE)
|
||||||
'ssid', ssid,
|
mark_ap_started()
|
||||||
'slave-type', 'bridge',
|
|
||||||
'master', bridge_name
|
|
||||||
]
|
|
||||||
r = subprocess.run(add_args, text=True, capture_output=True)
|
|
||||||
if r.returncode:
|
|
||||||
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé de créer la connexion en mode pont')
|
|
||||||
|
|
||||||
modify_args = [
|
|
||||||
'nmcli', 'connection', 'modify', name,
|
|
||||||
'802-11-wireless.mode', 'ap',
|
|
||||||
'802-11-wireless-security.key-mgmt', key,
|
|
||||||
'802-11-wireless-security.psk', password,
|
|
||||||
'802-11-wireless-security.pmf', pmf,
|
|
||||||
'802-11-wireless.band', AP_BAND,
|
|
||||||
'802-11-wireless.channel', str(AP_CHANNEL),
|
|
||||||
'connection.autoconnect', 'yes' if autoconnect else 'no'
|
|
||||||
]
|
|
||||||
if proto: modify_args += ['802-11-wireless-security.proto', proto]
|
|
||||||
if sec in ('wpa2', 'wpa3'):
|
|
||||||
modify_args += ['802-11-wireless-security.pairwise', 'ccmp', '802-11-wireless-security.group', 'ccmp']
|
|
||||||
r = subprocess.run(modify_args, text=True, capture_output=True)
|
|
||||||
if r.returncode:
|
|
||||||
raise RuntimeError(r.stderr.strip() or 'NetworkManager a refusé la configuration AP en mode pont')
|
|
||||||
else:
|
else:
|
||||||
teardown_bridge(bridge_name, bridge_eth)
|
teardown_bridge(bridge_name, bridge_eth)
|
||||||
|
ensure_nm_manages_wifi(INTERFACE)
|
||||||
add_args = [
|
add_args = [
|
||||||
'nmcli', 'connection', 'add',
|
'nmcli', 'connection', 'add',
|
||||||
'type', 'wifi',
|
'type', 'wifi',
|
||||||
@@ -4610,9 +4780,6 @@ def configure_ap(data, initial=False, caller_ip=None, start_now=True, silent=Fal
|
|||||||
r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True)
|
r = subprocess.run(['nmcli', 'connection', 'up', name], text=True, capture_output=True)
|
||||||
if r.returncode:
|
if r.returncode:
|
||||||
raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès')
|
raise RuntimeError(r.stderr.strip() or 'Impossible de démarrer le point d’accès')
|
||||||
if mode == 'bridge':
|
|
||||||
teardown_ap_nat()
|
|
||||||
else:
|
|
||||||
setup_ap_nat(INTERFACE)
|
setup_ap_nat(INTERFACE)
|
||||||
mark_ap_started()
|
mark_ap_started()
|
||||||
else:
|
else:
|
||||||
@@ -4668,7 +4835,29 @@ def restore_ap_from_db(force_start=False):
|
|||||||
target_name = get_pref('ap_connection_name', '') or ('AP-' + db_ssid)
|
target_name = get_pref('ap_connection_name', '') or ('AP-' + db_ssid)
|
||||||
should_start = bool(force_start or autoconnect)
|
should_start = bool(force_start or autoconnect)
|
||||||
|
|
||||||
# Vérifier si le profil NM existe déjà et correspond exactement à la BDD
|
# Mode Pont : géré nativement via hostapd (br0 reste non géré par NetworkManager)
|
||||||
|
if db_mode == 'bridge':
|
||||||
|
save_connection(target_name)
|
||||||
|
if should_start:
|
||||||
|
print(f"[ap-api] Démarrage du Wi-Fi Pont '{db_ssid}' depuis la BDD (pont={b_name}, sécurité={db_sec})...", flush=True)
|
||||||
|
try:
|
||||||
|
setup_bridge(b_name, b_eth)
|
||||||
|
start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE)
|
||||||
|
mark_ap_started()
|
||||||
|
invalidate_status_cache()
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ap-api] Erreur démarrage Pont hostapd : {e}", flush=True)
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
print(f"[ap-api] Profil Wi-Fi Pont '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
|
||||||
|
stop_hostapd(INTERFACE)
|
||||||
|
teardown_ap_nat()
|
||||||
|
invalidate_status_cache()
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Mode AP (NAT) : géré via NetworkManager + règles NAT/FORWARD
|
||||||
|
ensure_nm_manages_wifi(INTERFACE)
|
||||||
nm_exists = subprocess.run(['nmcli', 'connection', 'show', target_name], capture_output=True, text=True).returncode == 0
|
nm_exists = subprocess.run(['nmcli', 'connection', 'show', target_name], capture_output=True, text=True).returncode == 0
|
||||||
needs_rebuild = not nm_exists
|
needs_rebuild = not nm_exists
|
||||||
if nm_exists:
|
if nm_exists:
|
||||||
@@ -4680,17 +4869,17 @@ def restore_ap_from_db(force_start=False):
|
|||||||
nm_auto = command('nmcli', '-t', '-g', 'connection.autoconnect', 'connection', 'show', target_name).lower() == 'yes'
|
nm_auto = command('nmcli', '-t', '-g', 'connection.autoconnect', 'connection', 'show', target_name).lower() == 'yes'
|
||||||
nm_slave = (command('nmcli', '-t', '-g', 'connection.slave-type', 'connection', 'show', target_name) or command('nmcli', '-t', '-g', 'connection.port-type', 'connection', 'show', target_name)).lower()
|
nm_slave = (command('nmcli', '-t', '-g', 'connection.slave-type', 'connection', 'show', target_name) or command('nmcli', '-t', '-g', 'connection.port-type', 'connection', 'show', target_name)).lower()
|
||||||
nm_mode = 'bridge' if nm_slave == 'bridge' else 'ap'
|
nm_mode = 'bridge' if nm_slave == 'bridge' else 'ap'
|
||||||
if (nm_ssid != db_ssid or nm_pass != db_pass or nm_sec != db_sec or nm_auto != autoconnect or nm_mode != db_mode):
|
if (nm_ssid != db_ssid or nm_pass != db_pass or nm_sec != db_sec or nm_auto != autoconnect or nm_mode != 'ap'):
|
||||||
needs_rebuild = True
|
needs_rebuild = True
|
||||||
|
|
||||||
if needs_rebuild:
|
if needs_rebuild:
|
||||||
print(f"[ap-api] Reconstruction du profil Wi-Fi '{db_ssid}' depuis la BDD (mode={db_mode}, sécurité={db_sec}, autoconnect={'oui' if autoconnect else 'non'})...", flush=True)
|
print(f"[ap-api] Reconstruction du profil Wi-Fi '{db_ssid}' depuis la BDD (mode=ap, sécurité={db_sec}, autoconnect={'oui' if autoconnect else 'non'})...", flush=True)
|
||||||
try:
|
try:
|
||||||
configure_ap({
|
configure_ap({
|
||||||
'ssid': db_ssid,
|
'ssid': db_ssid,
|
||||||
'password': db_pass,
|
'password': db_pass,
|
||||||
'security': db_sec,
|
'security': db_sec,
|
||||||
'mode': db_mode,
|
'mode': 'ap',
|
||||||
'autoconnect': autoconnect,
|
'autoconnect': autoconnect,
|
||||||
'bridge_name': b_name,
|
'bridge_name': b_name,
|
||||||
'bridge_eth': b_eth
|
'bridge_eth': b_eth
|
||||||
@@ -4703,27 +4892,20 @@ def restore_ap_from_db(force_start=False):
|
|||||||
# Le profil NM existe déjà et correspond à la BDD
|
# Le profil NM existe déjà et correspond à la BDD
|
||||||
save_connection(target_name)
|
save_connection(target_name)
|
||||||
if should_start:
|
if should_start:
|
||||||
if db_mode == 'bridge':
|
|
||||||
clean_stale_router_leases()
|
|
||||||
setup_bridge(b_name, b_eth)
|
|
||||||
else:
|
|
||||||
teardown_bridge(b_name, b_eth)
|
teardown_bridge(b_name, b_eth)
|
||||||
|
ensure_nm_manages_wifi(INTERFACE)
|
||||||
state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE)
|
state = command('nmcli', '-t', '-g', 'GENERAL.STATE', 'device', 'show', INTERFACE)
|
||||||
if not state.startswith('100'):
|
if not state.startswith('100'):
|
||||||
print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode={db_mode})...", flush=True)
|
print(f"[ap-api] Démarrage automatique du Wi-Fi '{db_ssid}' (mode=ap)...", flush=True)
|
||||||
r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True)
|
r = subprocess.run(['nmcli', 'connection', 'up', target_name], capture_output=True, text=True)
|
||||||
if r.returncode != 0:
|
if r.returncode != 0:
|
||||||
print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True)
|
print(f"[ap-api] Erreur démarrage automatique '{target_name}' : {r.stderr.strip()}", flush=True)
|
||||||
return False
|
return False
|
||||||
if db_mode == 'bridge':
|
|
||||||
teardown_ap_nat()
|
|
||||||
else:
|
|
||||||
setup_ap_nat(INTERFACE)
|
setup_ap_nat(INTERFACE)
|
||||||
mark_ap_started()
|
mark_ap_started()
|
||||||
else:
|
else:
|
||||||
print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
|
print(f"[ap-api] Profil Wi-Fi '{db_ssid}' restauré depuis la BDD (démarrage automatique désactivé).", flush=True)
|
||||||
teardown_ap_nat()
|
teardown_ap_nat()
|
||||||
if db_mode != 'bridge':
|
|
||||||
teardown_bridge(b_name, b_eth)
|
teardown_bridge(b_name, b_eth)
|
||||||
invalidate_status_cache()
|
invalidate_status_cache()
|
||||||
return True
|
return True
|
||||||
@@ -8176,25 +8358,38 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if self.path == '/api/ap/control':
|
if self.path == '/api/ap/control':
|
||||||
action=str(data.get('action','')); name=connection_name()
|
action=str(data.get('action','')); name=connection_name()
|
||||||
if not name and not get_pref('ap_ssid', ''): raise ValueError('Aucune connexion AP configurée')
|
if not name and not get_pref('ap_ssid', ''): raise ValueError('Aucune connexion AP configurée')
|
||||||
|
if is_bridge_mode():
|
||||||
|
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
||||||
|
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
||||||
if action in ('start', 'restart'):
|
if action in ('start', 'restart'):
|
||||||
|
db_ssid = (get_pref('ap_ssid', '') or '').strip()
|
||||||
|
db_pass = get_pref('ap_password', '') or ''
|
||||||
|
db_sec = (get_pref('ap_security', 'wpa2') or 'wpa2').lower()
|
||||||
|
if not db_ssid or not db_pass:
|
||||||
|
raise RuntimeError('Paramètres Wi-Fi manquants en BDD : veuillez ré-enregistrer les réglages Wi-Fi')
|
||||||
|
if action == 'restart':
|
||||||
|
stop_hostapd(INTERFACE)
|
||||||
|
setup_bridge(b_name, b_eth)
|
||||||
|
start_bridge_hostapd(db_ssid, db_pass, sec=db_sec, bridge_name=b_name, iface=INTERFACE)
|
||||||
|
mark_ap_started()
|
||||||
|
elif action == 'stop':
|
||||||
|
stop_hostapd(INTERFACE)
|
||||||
|
teardown_bridge_dns_redirection(b_name, INTERFACE)
|
||||||
|
try: os.remove(UPTIME_FILE)
|
||||||
|
except OSError: pass
|
||||||
|
else:
|
||||||
|
if action in ('start', 'restart'):
|
||||||
|
ensure_nm_manages_wifi(INTERFACE)
|
||||||
nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True).returncode == 0)
|
nm_exists = bool(name) and (subprocess.run(['nmcli', 'connection', 'show', name], capture_output=True, text=True).returncode == 0)
|
||||||
if not nm_exists and get_pref('ap_ssid', ''):
|
if not nm_exists and get_pref('ap_ssid', ''):
|
||||||
if not restore_ap_from_db(force_start=True):
|
if not restore_ap_from_db(force_start=True):
|
||||||
raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD')
|
raise RuntimeError('Impossible de restaurer et démarrer la connexion Wi-Fi depuis la BDD')
|
||||||
else:
|
else:
|
||||||
if is_bridge_mode():
|
|
||||||
b_name = get_pref('bridge_name', os.environ.get('AP_BRIDGE_NAME', 'br0'))
|
|
||||||
b_eth = get_pref('bridge_eth', os.environ.get('AP_BRIDGE_ETH', ''))
|
|
||||||
clean_stale_router_leases()
|
|
||||||
setup_bridge(b_name, b_eth)
|
|
||||||
if action == 'restart':
|
if action == 'restart':
|
||||||
subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True)
|
subprocess.run(['nmcli', 'connection', 'down', name], capture_output=True, text=True)
|
||||||
r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True)
|
r = subprocess.run(['nmcli', 'connection', 'up', name], capture_output=True, text=True)
|
||||||
if r.returncode: raise RuntimeError(r.stderr.strip())
|
if r.returncode: raise RuntimeError(r.stderr.strip())
|
||||||
if not is_bridge_mode():
|
|
||||||
setup_ap_nat(INTERFACE)
|
setup_ap_nat(INTERFACE)
|
||||||
else:
|
|
||||||
teardown_ap_nat()
|
|
||||||
mark_ap_started()
|
mark_ap_started()
|
||||||
elif action == 'stop':
|
elif action == 'stop':
|
||||||
if name:
|
if name:
|
||||||
|
|||||||
@@ -313,6 +313,13 @@ WEB_PID=$!
|
|||||||
cleanup() {
|
cleanup() {
|
||||||
trap - EXIT TERM INT
|
trap - EXIT TERM INT
|
||||||
log "Arrêt des services et nettoyage..."
|
log "Arrêt des services et nettoyage..."
|
||||||
|
# Arrêt propre de hostapd (mode pont) et détachement de l'interface Wi-Fi sans toucher au pont hôte
|
||||||
|
if [[ -f /run/ap-hostapd.pid ]]; then
|
||||||
|
kill "$(cat /run/ap-hostapd.pid 2>/dev/null || true)" 2>/dev/null || true
|
||||||
|
rm -f /run/ap-hostapd.pid /run/ap-hostapd.conf 2>/dev/null || true
|
||||||
|
fi
|
||||||
|
pkill -f '/run/ap-hostapd.conf' 2>/dev/null || true
|
||||||
|
[[ -n "${IFACE:-}" ]] && ip link set "$IFACE" nomaster 2>/dev/null || true
|
||||||
# Suppression du fichier d'uptime lors de l'arrêt du conteneur
|
# Suppression du fichier d'uptime lors de l'arrêt du conteneur
|
||||||
rm -f "${AP_UPTIME_FILE:-/data/uptime}" /app/ap-dashboard-uptime 2>/dev/null || true
|
rm -f "${AP_UPTIME_FILE:-/data/uptime}" /app/ap-dashboard-uptime 2>/dev/null || true
|
||||||
# Restauration uniquement d'un pont créé par APmanageur (/run/ap-created-bridge)
|
# Restauration uniquement d'un pont créé par APmanageur (/run/ap-created-bridge)
|
||||||
|
|||||||
Reference in new issue
Block a user