fix: detect and auto-configure rp_filter to loose mode (2) to prevent policy routing packet loss

This commit is contained in:
baoweise-bot
2026-05-30 15:04:47 +08:00
parent 28c32c59d2
commit 5a49d09e69
3 changed files with 46 additions and 0 deletions
+30
View File
@@ -1020,6 +1020,36 @@ with open('$AUTH_FILE', 'w', encoding='utf-8') as f:
fi
# 8. Start service
# 8.5 Optimize network parameters (rp_filter for policy routing)
echo -e "\n正在优化网络参数 (配置反向路径过滤 rp_filter=2 以支持策略路由)..."
if [ -d "/etc/sysctl.d" ]; then
cat > /etc/sysctl.d/99-aimilivpn.conf <<EOF
net.ipv4.conf.all.rp_filter = 2
net.ipv4.conf.default.rp_filter = 2
EOF
sysctl -p /etc/sysctl.d/99-aimilivpn.conf >/dev/null 2>&1 || true
else
# Fallback to appending to /etc/sysctl.conf
if ! grep -q "net.ipv4.conf.all.rp_filter" /etc/sysctl.conf; then
echo "" >> /etc/sysctl.conf
echo "net.ipv4.conf.all.rp_filter = 2" >> /etc/sysctl.conf
echo "net.ipv4.conf.default.rp_filter = 2" >> /etc/sysctl.conf
else
sed -i 's/net.ipv4.conf.all.rp_filter\s*=\s*[0-9]/net.ipv4.conf.all.rp_filter = 2/g' /etc/sysctl.conf
sed -i 's/net.ipv4.conf.default.rp_filter\s*=\s*[0-9]/net.ipv4.conf.default.rp_filter = 2/g' /etc/sysctl.conf
fi
sysctl -p >/dev/null 2>&1 || true
fi
# Apply to currently active interfaces dynamically
sysctl -w net.ipv4.conf.all.rp_filter=2 >/dev/null 2>&1 || true
sysctl -w net.ipv4.conf.default.rp_filter=2 >/dev/null 2>&1 || true
if [ -d "/proc/sys/net/ipv4/conf" ]; then
for dev_dir in /proc/sys/net/ipv4/conf/*; do
dev_name=$(basename "$dev_dir")
sysctl -w net.ipv4.conf.${dev_name}.rp_filter=2 >/dev/null 2>&1 || true
done
fi
echo -e "\n正在启动 AimiliVPN 服务并初始化网络..."
if command -v systemctl >/dev/null 2>&1; then
systemctl restart aimilivpn.service || true
+10
View File
@@ -611,4 +611,14 @@ def diagnose_local_obstructions(proxy_port: int = 7928, host: str = "127.0.0.1")
except Exception:
pass
# 4. 检查系统反向路径过滤 (rp_filter) 设置
rp_all_path = Path("/proc/sys/net/ipv4/conf/all/rp_filter")
if rp_all_path.exists():
try:
val = rp_all_path.read_text(encoding="utf-8").strip()
if val == "1":
return 3008, "[ERR_ROUTE_RP_FILTER_STRICT] 系统启用了严格的反向路径过滤(rp_filter=1)。原因: 在启用策略路由时,严格的路径过滤会导致通过虚拟网卡 tun0 的回包被内核静默丢弃,导致连接超时。请将 net.ipv4.conf.all.rp_filter 设置为 2 或 0。"
except Exception:
pass
return None
+6
View File
@@ -598,6 +598,12 @@ def setup_policy_routing(interface: str = "tun0") -> None:
try:
subprocess.run(["ip", "route", "add", "default", "dev", interface, "table", "100"], check=True, timeout=2)
subprocess.run(["ip", "rule", "add", "oif", interface, "table", "100"], check=True, timeout=2)
# 配置反向路径过滤 rp_filter 为 loose 模式 (2),防止回包被内核静默丢弃
for proc_path in ["all", "default", interface]:
try:
subprocess.run(["sysctl", "-w", f"net.ipv4.conf.{proc_path}.rp_filter=2"], capture_output=True, timeout=2)
except Exception:
pass
print(f"[policy_routing] Enabled policy routing for interface {interface} (attempt {attempt} success)", flush=True)
success = True
break