> ## Documentation Index
> Fetch the complete documentation index at: https://e-gurl.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenWrt Features

> Comprehensive OpenWrt features including hot-reload, split-horizon DNS, per-device policies, and more

# DNS-MNS OpenWrt Features

This document describes the comprehensive OpenWrt support added to DNS-MNS v6.4.0.

## Overview

DNS-MNS now includes extensive OpenWrt router support with the following key features:

* **Hot-reload configuration** - Change settings without restart
* **Split-horizon DNS** - Route domains to different DNS servers
* **Per-device policies** - Different DNS for different clients
* **Auto-benchmarking** - Automatically switch to best DNS
* **VPN-aware routing** - Change DNS based on VPN status
* **Multi-WAN support** - Route DNS through specific WANs
* **Transparent proxy** - Intercept all DNS traffic
* **Metrics & logging** - Comprehensive monitoring
* **LuCI web interface** - Web-based configuration
* **AdGuard integration** - Work with AdGuard Home
* **mDNS support** - Local service discovery
* **Notifications** - Telegram/Discord alerts

## Package Structure

```
internal/openwrt/
├── service/       # Service lifecycle management
├── config/        # Enhanced configuration
├── ubus/          # OpenWrt system bus integration
├── splitdns/      # Split-horizon DNS
├── policy/        # Per-device policies
├── scheduler/     # Auto-benchmarking
├── vpn/           # VPN-aware routing
├── multiwan/      # Multi-WAN support
├── firewall/      # Transparent proxy
├── metrics/       # Metrics collection
├── logging/       # Query logging
├── adguard/       # AdGuard Home integration
├── mdns/          # mDNS resolver
└── bot/           # Notification bot
```

## Features

### 1. Service Management (`service/`)

* Hot-reload support via SIGHUP signal
* Graceful start/stop with cleanup
* Health check monitoring
* Signal handling for proper shutdown

```go theme={null}
manager := service.NewManager(handler)
manager.Start(config)
manager.TriggerReload() // Hot-reload
manager.Stop()
```

### 2. Configuration (`config/`)

* JSON-based configuration with UCI fallback
* Atomic config writes
* Import/export functionality
* Version tracking

### 3. Split-Horizon DNS (`splitdns/`)

Route different domains to different DNS servers:

```go theme={null}
resolver.AddRule(&splitdns.Rule{
    Domain:     ".ir",
    DNSServers: []string{"178.22.122.100"}, // Iranian DNS
    Priority:   100,
})

resolver.AddRule(&splitdns.Rule{
    Domain:     "*.local",
    DNSServers: []string{"127.0.0.1"}, // Local
    Priority:   200,
})
```

### 4. Per-Device Policies (`policy/`)

Apply different DNS settings based on device:

```go theme={null}
engine.AddPolicy(&policy.ClientPolicy{
    ID:           "kids-safe",
    Type:         policy.PolicyTypeDevice,
    MatchValue:   "aa:bb:cc:dd:ee:ff",
    PrimaryDNS:   "1.1.1.3", // Cloudflare for Families
    BlockAds:     true,
    SafeSearch:   true,
})
```

Preset policies available:

* `kids-safe` - Safe browsing with ad blocking
* `gaming-optimized` - Low-latency DNS for gaming
* `iot-restricted` - Restricted DNS for IoT devices
* `guest-network` - Standard DNS for guests

### 5. Auto-Benchmarking (`scheduler/`)

Automatically test and switch to the best DNS:

```go theme={null}
scheduler := scheduler.NewScheduler(config)
scheduler.SetCallbacks(
    onDNSChange,      // Called when DNS switches
    onBenchmarkStart, // Called when benchmark starts
    onBenchmarkComplete,
)
scheduler.Start()
```

Features:

* Configurable benchmark interval
* Automatic failover on failures
* Performance-based switching
* Health checker with configurable threshold

### 6. VPN Integration (`vpn/`)

Change DNS based on VPN connection status:

```go theme={null}
monitor.AddPolicy(&vpn.Policy{
    VPNInterface: "wg0",
    DNSWhenUp:    []string{"10.0.0.1"},     // VPN DNS
    DNSWhenDown:  []string{"1.1.1.1"},      // Regular DNS
    KillSwitch:   true,                       // Block DNS when VPN down
})
```

Supported VPN types:

* WireGuard
* OpenVPN
* sing-box

### 7. Multi-WAN Support (`multiwan/`)

Route DNS through specific WAN interfaces:

```go theme={null}
router.AddWAN(&multiwan.WAN{
    ID:         "wan1",
    Interface:  "eth0",
    DNSServers: []string{"1.1.1.1"},
    Priority:   1,  // Higher priority
    FailoverTo: "wan2",
})
```

Features:

* Per-WAN DNS configuration
* Automatic failover
* Health checking with latency monitoring
* Priority-based selection

### 8. Transparent Proxy (`firewall/`)

Intercept all DNS traffic for redirection:

```go theme={null}
manager := firewall.NewManager(firewall.BackendIPTables, 5353)
manager.Setup()    // Add firewall rules
manager.Cleanup()  // Remove rules
```

Supports:

* iptables backend
* nftables backend
* Client exclusion list

### 9. Metrics (`metrics/`)

Collect and export DNS query statistics:

```go theme={null}
collector := metrics.NewCollector(10000, true, 24*time.Hour)
collector.RecordQuery(record)

// Prometheus export
exporter := metrics.NewPrometheusExporter(collector)
http.Handle("/metrics", exporter)
```

Features:

* Query record collection
* Top domains/clients tracking
* Per-server statistics
* Prometheus exposition format

### 10. Logging (`logging/`)

Structured DNS query logging:

```go theme={null}
logger, _ := logging.NewLogger(config)
logger.LogQuery(clientIP, domain, queryType)
logger.LogResponse(clientIP, domain, serverUsed, responseTime, cached)
```

Features:

* JSON log format
* Automatic rotation
* IP anonymization
* Configurable log levels

### 11. AdGuard Integration (`adguard/`)

Integrate with AdGuard Home:

```go theme={null}
ag := adguard.NewIntegration(config)
if ag.IsInstalled() && ag.IsRunning() {
    ag.ConfigureUpstream("127.0.0.1:5353")
}
```

### 12. mDNS Support (`mdns/`)

Local service discovery:

```go theme={null}
resolver := mdns.NewResolver(config)
resolver.Start()
ips, _ := resolver.Resolve("printer.local")
```

### 13. Notifications (`bot/`)

Send alerts via Telegram or Discord:

```go theme={null}
notifier := bot.NewNotifier(config)
notifier.SendAlert("DNS Failure", "Primary DNS is down")
notifier.SendStats(stats)
```

## LuCI Web Interface

The LuCI interface provides web-based configuration:

```
Services → DNS-MNS
├── Status         - Service status and statistics
├── General        - Basic settings
├── DNS Servers    - Upstream DNS configuration
├── Split-Horizon  - Domain-based routing
├── Policies       - Per-device policies
├── VPN            - VPN-aware routing
├── Multi-WAN      - WAN-specific DNS
├── Firewall       - Transparent proxy
├── Logging        - Log configuration
├── View Logs      - Real-time log viewer
└── Statistics     - Query statistics
```

## Installation

### Package Installation

```bash theme={null}
opkg update
opkg install dns-mns luci-app-dns-mns
```

### Manual Installation

```bash theme={null}
# Copy binary
scp dns-mns-openwrt-x86_64 root@router:/usr/bin/dns-mns
ssh root@router chmod +x /usr/bin/dns-mns

# Install init script
cp scripts/openwrt/dns-mns.init /etc/init.d/dns-mns
chmod +x /etc/init.d/dns-mns

# Install LuCI files
cp -r scripts/openwrt/luci/* /usr/lib/lua/luci/
```

## Configuration

### UCI Configuration

```bash theme={null}
# Enable DNS-MNS
uci set dns-mns.main.enabled=1
uci set dns-mns.main.mode=upstream
uci set dns-mns.main.listen_addr=127.0.0.1
uci set dns-mns.main.listen_port=5353

# Configure split-horizon DNS
uci add dns-mns splitdns
uci set dns-mns.@splitdns[-1].domain=.ir
uci set dns-mns.@splitdns[-1].dns_servers=178.22.122.100

# Commit changes
uci commit dns-mns
/etc/init.d/dns-mns restart
```

### JSON Configuration

```json theme={null}
{
  "version": "6.4.0",
  "enabled": true,
  "mode": "upstream",
  "listen_addr": "127.0.0.1",
  "listen_port": 5353,
  "scheduler_enabled": true,
  "benchmark_interval": 21600000000000,
  "logging_enabled": true,
  "log_level": "info"
}
```

## API Examples

### ubus Integration

```bash theme={null}
# Get status
ubus call dns-mns status

# Reload configuration
ubus call dns-mns reload

# Get statistics
ubus call dns-mns stats
```

### CLI Commands

```bash theme={null}
# OpenWrt-specific commands
dns-mns openwrt detect
dns-mns openwrt setup --mode upstream
dns-mns openwrt status
dns-mns openwrt restore

# VPN commands
dns-mns vpn status
dns-mns vpn add-policy --interface wg0

# Multi-WAN commands
dns-mns multiwan status
dns-mns multiwan add-wan --interface eth0

# Firewall commands
dns-mns firewall enable
dns-mns firewall disable

# Metrics
dns-mns metrics export
dns-mns metrics serve --port 9090
```

## Testing

All packages include comprehensive tests:

```bash theme={null}
# Run all tests
go test ./internal/openwrt/...

# Run with coverage
go test -cover ./internal/openwrt/...

# Run specific package tests
go test ./internal/openwrt/splitdns/...
go test ./internal/openwrt/policy/...
```

## Troubleshooting

### Check Service Status

```bash theme={null}
/etc/init.d/dns-mns status
logread -f | grep dns-mns
```

### Test DNS Resolution

```bash theme={null}
# Test through DNS-MNS
dig @127.0.0.1 -p 5353 google.com

# Check upstream DNS
uci get dhcp.@dnsmasq[0].server
```

### Debug Mode

```bash theme={null}
# Enable debug logging
uci set dns-mns.main.log_level=debug
uci commit dns-mns
/etc/init.d/dns-mns restart
```

## Migration from Older Versions

1. Backup existing configuration:

```bash theme={null}
cp /etc/config/dns-mns /etc/config/dns-mns.backup
```

2. Install new version
3. Run migration helper:

```bash theme={null}
dns-mns migrate --from 6.3.1
```

4. Verify configuration:

```bash theme={null}
dns-mns config validate
```

## License

MIT License - See LICENSE file for details.
