Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1d425069f | ||
|
|
d274500308 | ||
|
|
9c313ef06a | ||
|
|
0d25fae4cf | ||
|
|
1ae2e23bb6 | ||
|
|
fe784addd2 |
15
.github/workflows/release.yml
vendored
15
.github/workflows/release.yml
vendored
@@ -79,8 +79,21 @@ jobs:
|
|||||||
${{ matrix.name }}.zip
|
${{ matrix.name }}.zip
|
||||||
${{ matrix.name }}.zip.sha256
|
${{ matrix.name }}.zip.sha256
|
||||||
|
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install Rust
|
||||||
|
uses: dtolnay/rust-toolchain@stable
|
||||||
|
|
||||||
|
- name: Publish to crates.io
|
||||||
|
run: cargo publish
|
||||||
|
env:
|
||||||
|
CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
|
||||||
|
|
||||||
release:
|
release:
|
||||||
needs: build
|
needs: [build, publish]
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/download-artifact@v4
|
- uses: actions/download-artifact@v4
|
||||||
|
|||||||
39
Cargo.lock
generated
39
Cargo.lock
generated
@@ -67,6 +67,15 @@ dependencies = [
|
|||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arc-swap"
|
||||||
|
version = "1.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a07d1f37ff60921c83bdfc7407723bdefe89b44b98a9b772f225c8f9d67141a6"
|
||||||
|
dependencies = [
|
||||||
|
"rustversion",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "asn1-rs"
|
name = "asn1-rs"
|
||||||
version = "0.6.2"
|
version = "0.6.2"
|
||||||
@@ -384,6 +393,12 @@ dependencies = [
|
|||||||
"miniz_oxide",
|
"miniz_oxide",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fnv"
|
||||||
|
version = "1.0.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
@@ -514,6 +529,25 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "h2"
|
||||||
|
version = "0.4.13"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"
|
||||||
|
dependencies = [
|
||||||
|
"atomic-waker",
|
||||||
|
"bytes",
|
||||||
|
"fnv",
|
||||||
|
"futures-core",
|
||||||
|
"futures-sink",
|
||||||
|
"http",
|
||||||
|
"indexmap",
|
||||||
|
"slab",
|
||||||
|
"tokio",
|
||||||
|
"tokio-util",
|
||||||
|
"tracing",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.16.1"
|
version = "0.16.1"
|
||||||
@@ -575,6 +609,7 @@ dependencies = [
|
|||||||
"bytes",
|
"bytes",
|
||||||
"futures-channel",
|
"futures-channel",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
|
"h2",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"httparse",
|
"httparse",
|
||||||
@@ -932,8 +967,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "numa"
|
name = "numa"
|
||||||
version = "0.4.0"
|
version = "0.5.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"arc-swap",
|
||||||
"axum",
|
"axum",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"futures",
|
"futures",
|
||||||
@@ -1201,6 +1237,7 @@ dependencies = [
|
|||||||
"base64",
|
"base64",
|
||||||
"bytes",
|
"bytes",
|
||||||
"futures-core",
|
"futures-core",
|
||||||
|
"h2",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"http-body-util",
|
"http-body-util",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "numa"
|
name = "numa"
|
||||||
version = "0.4.0"
|
version = "0.5.0"
|
||||||
authors = ["razvandimescu <razvan@dimescu.com>"]
|
authors = ["razvandimescu <razvan@dimescu.com>"]
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
description = "Ephemeral DNS overrides for development and testing. Point any hostname to any endpoint. Auto-revert when you're done."
|
description = "Ephemeral DNS overrides for development and testing. Point any hostname to any endpoint. Auto-revert when you're done."
|
||||||
@@ -17,7 +17,7 @@ serde_json = "1"
|
|||||||
toml = "0.8"
|
toml = "0.8"
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
env_logger = "0.11"
|
env_logger = "0.11"
|
||||||
reqwest = { version = "0.12", features = ["rustls-tls", "gzip"], default-features = false }
|
reqwest = { version = "0.12", features = ["rustls-tls", "gzip", "http2"], default-features = false }
|
||||||
hyper = { version = "1", features = ["client", "http1", "server"] }
|
hyper = { version = "1", features = ["client", "http1", "server"] }
|
||||||
hyper-util = { version = "0.1", features = ["client-legacy", "http1", "tokio"] }
|
hyper-util = { version = "0.1", features = ["client-legacy", "http1", "tokio"] }
|
||||||
http-body-util = "0.1"
|
http-body-util = "0.1"
|
||||||
@@ -27,3 +27,4 @@ rcgen = { version = "0.13", features = ["pem", "x509-parser"] }
|
|||||||
time = "0.3"
|
time = "0.3"
|
||||||
rustls = "0.23"
|
rustls = "0.23"
|
||||||
tokio-rustls = "0.26"
|
tokio-rustls = "0.26"
|
||||||
|
arc-swap = "1"
|
||||||
|
|||||||
22
README.md
22
README.md
@@ -15,7 +15,9 @@ Built from scratch in Rust. Zero DNS libraries. RFC 1035 wire protocol parsed by
|
|||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Install
|
# Install (pick one)
|
||||||
|
brew install razvandimescu/tap/numa
|
||||||
|
cargo install numa
|
||||||
curl -fsSL https://raw.githubusercontent.com/razvandimescu/numa/main/install.sh | sh
|
curl -fsSL https://raw.githubusercontent.com/razvandimescu/numa/main/install.sh | sh
|
||||||
|
|
||||||
# Run (port 53 requires root)
|
# Run (port 53 requires root)
|
||||||
@@ -37,11 +39,12 @@ sudo ./target/release/numa
|
|||||||
|
|
||||||
## Why Numa
|
## Why Numa
|
||||||
|
|
||||||
- **Ad blocking that travels with you** — 385K+ domains blocked via [Hagezi Pro](https://github.com/hagezi/dns-blocklists). Works on any network: coffee shops, hotels, airports.
|
- **Local service proxy** — `https://frontend.numa` instead of `localhost:5173`. Auto-generated TLS certs, WebSocket support for HMR. Like `/etc/hosts` but with auto TLS, a REST API, LAN discovery, and auto-revert.
|
||||||
- **Local service proxy** — `https://frontend.numa` instead of `localhost:5173`. Auto-generated TLS certs, WebSocket support for HMR. Like `/etc/hosts` but with a dashboard and auto-revert.
|
|
||||||
- **Path-based routing** — `app.numa/api → :5001`, `app.numa/auth → :5002`. Route URL paths to different backends with optional prefix stripping. Like nginx location blocks, zero config files.
|
- **Path-based routing** — `app.numa/api → :5001`, `app.numa/auth → :5002`. Route URL paths to different backends with optional prefix stripping. Like nginx location blocks, zero config files.
|
||||||
- **LAN service discovery** — Numa instances on the same network find each other automatically via mDNS. Access a teammate's `api.numa` from your machine. Opt-in via `[lan] enabled = true`.
|
- **LAN service discovery** — Numa instances on the same network find each other automatically via mDNS. Access a teammate's `api.numa` from your machine. Opt-in via `[lan] enabled = true`.
|
||||||
- **Developer overrides** — point any hostname to any IP, auto-reverts after N minutes. REST API with 25+ endpoints. Built-in diagnostics: `curl localhost:5380/diagnose/example.com` tells you exactly how any domain resolves.
|
- **Developer overrides** — point any hostname to any IP, auto-reverts after N minutes. REST API with 25+ endpoints. Built-in diagnostics: `curl localhost:5380/diagnose/example.com` tells you exactly how any domain resolves.
|
||||||
|
- **DNS-over-HTTPS** — upstream queries encrypted via DoH. Your ISP sees HTTPS traffic, not DNS queries. Set `address = "https://9.9.9.9/dns-query"` in `[upstream]` or any DoH provider.
|
||||||
|
- **Ad blocking that travels with you** — 385K+ domains blocked via [Hagezi Pro](https://github.com/hagezi/dns-blocklists). Works on any network: coffee shops, hotels, airports.
|
||||||
- **Sub-millisecond caching** — cached lookups in 0ms. Faster than any public resolver.
|
- **Sub-millisecond caching** — cached lookups in 0ms. Faster than any public resolver.
|
||||||
- **Live dashboard** — real-time stats, query log, blocking controls, service management. LAN accessibility badges show which services are reachable from other devices.
|
- **Live dashboard** — real-time stats, query log, blocking controls, service management. LAN accessibility badges show which services are reachable from other devices.
|
||||||
- **macOS + Linux** — `numa install` configures system DNS, `numa service start` runs as launchd/systemd service.
|
- **macOS + Linux** — `numa install` configures system DNS, `numa service start` runs as launchd/systemd service.
|
||||||
@@ -128,15 +131,15 @@ bind_addr = "0.0.0.0:53"
|
|||||||
|
|
||||||
| | Pi-hole | AdGuard Home | NextDNS | Cloudflare | Numa |
|
| | Pi-hole | AdGuard Home | NextDNS | Cloudflare | Numa |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
| Ad blocking | Yes | Yes | Yes | Limited | 385K+ domains |
|
|
||||||
| Portable (travels with laptop) | No (appliance) | No (appliance) | Cloud only | Cloud only | Single binary |
|
|
||||||
| Developer overrides | No | No | No | No | REST API + auto-expiry |
|
|
||||||
| Local service proxy | No | No | No | No | `.numa` + HTTPS + WS |
|
| Local service proxy | No | No | No | No | `.numa` + HTTPS + WS |
|
||||||
| Path-based routing | No | No | No | No | Prefix match + strip |
|
| Path-based routing | No | No | No | No | Prefix match + strip |
|
||||||
| LAN service discovery | No | No | No | No | mDNS, opt-in |
|
| LAN service discovery | No | No | No | No | mDNS, opt-in |
|
||||||
| Data stays local | Yes | Yes | Cloud | Cloud | 100% local |
|
| Developer overrides | No | No | No | No | REST API + auto-expiry |
|
||||||
|
| Encrypted upstream (DoH) | No (needs cloudflared) | Yes | Cloud only | Cloud only | Native, single binary |
|
||||||
|
| Portable (travels with laptop) | No (appliance) | No (appliance) | Cloud only | Cloud only | Single binary |
|
||||||
| Zero config | Complex | Docker/setup | Yes | Yes | Works out of the box |
|
| Zero config | Complex | Docker/setup | Yes | Yes | Works out of the box |
|
||||||
| Self-sovereign DNS | No | No | No | No | pkarr/DHT roadmap |
|
| Ad blocking | Yes | Yes | Yes | Limited | 385K+ domains |
|
||||||
|
| Data stays local | Yes | Yes | Cloud | Cloud | 100% local |
|
||||||
|
|
||||||
## How It Works
|
## How It Works
|
||||||
|
|
||||||
@@ -144,7 +147,7 @@ bind_addr = "0.0.0.0:53"
|
|||||||
Query → Overrides → .numa TLD → Blocklist → Local Zones → Cache → Upstream
|
Query → Overrides → .numa TLD → Blocklist → Local Zones → Cache → Upstream
|
||||||
```
|
```
|
||||||
|
|
||||||
No DNS libraries. The wire protocol — headers, labels, compression pointers, record types — is parsed and serialized by hand. Runs on `tokio` + `axum`, async per-query task spawning.
|
No DNS libraries — no `hickory-dns`, no `trust-dns`. The wire protocol — headers, labels, compression pointers, record types — is parsed and serialized by hand. Runs on `tokio` + `axum`, async per-query task spawning.
|
||||||
|
|
||||||
[Configuration reference](numa.toml)
|
[Configuration reference](numa.toml)
|
||||||
|
|
||||||
@@ -157,6 +160,7 @@ No DNS libraries. The wire protocol — headers, labels, compression pointers, r
|
|||||||
- [x] Local service proxy — `.numa` domains, HTTP/HTTPS proxy, auto TLS, WebSocket
|
- [x] Local service proxy — `.numa` domains, HTTP/HTTPS proxy, auto TLS, WebSocket
|
||||||
- [x] Path-based routing — URL prefix routing with optional strip, REST API
|
- [x] Path-based routing — URL prefix routing with optional strip, REST API
|
||||||
- [x] LAN service discovery — mDNS auto-discovery (opt-in), cross-machine DNS + proxy
|
- [x] LAN service discovery — mDNS auto-discovery (opt-in), cross-machine DNS + proxy
|
||||||
|
- [x] DNS-over-HTTPS — encrypted upstream via DoH (Quad9, Cloudflare, any provider)
|
||||||
- [ ] pkarr integration — self-sovereign DNS via Mainline DHT (15M nodes)
|
- [ ] pkarr integration — self-sovereign DNS via Mainline DHT (15M nodes)
|
||||||
- [ ] Global `.numa` names — self-publish, DHT-backed, first-come-first-served
|
- [ ] Global `.numa` names — self-publish, DHT-backed, first-come-first-served
|
||||||
|
|
||||||
|
|||||||
@@ -4,9 +4,11 @@ api_port = 5380
|
|||||||
# api_bind_addr = "127.0.0.1" # default; set to "0.0.0.0" for LAN dashboard access
|
# api_bind_addr = "127.0.0.1" # default; set to "0.0.0.0" for LAN dashboard access
|
||||||
|
|
||||||
# [upstream]
|
# [upstream]
|
||||||
# address = "" # auto-detect from system resolver (default)
|
# address = "" # auto-detect from system resolver (default)
|
||||||
# address = "9.9.9.9" # or set explicitly
|
# address = "https://dns.quad9.net/dns-query" # DNS-over-HTTPS (encrypted)
|
||||||
# port = 53
|
# address = "https://cloudflare-dns.com/dns-query" # Cloudflare DoH
|
||||||
|
# address = "9.9.9.9" # plain UDP
|
||||||
|
# port = 53 # only used for plain UDP
|
||||||
# timeout_ms = 3000
|
# timeout_ms = 3000
|
||||||
|
|
||||||
# [blocking]
|
# [blocking]
|
||||||
|
|||||||
17
src/api.rs
17
src/api.rs
@@ -9,7 +9,7 @@ use axum::{Json, Router};
|
|||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::ctx::ServerCtx;
|
use crate::ctx::ServerCtx;
|
||||||
use crate::forward::forward_query;
|
use crate::forward::{forward_query, Upstream};
|
||||||
use crate::query_log::QueryLogFilter;
|
use crate::query_log::QueryLogFilter;
|
||||||
use crate::question::QueryType;
|
use crate::question::QueryType;
|
||||||
use crate::stats::QueryPath;
|
use crate::stats::QueryPath;
|
||||||
@@ -355,9 +355,9 @@ async fn diagnose(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check upstream (async, no locks held)
|
// Check upstream (async, no locks held)
|
||||||
let upstream = *ctx.upstream.lock().unwrap();
|
let upstream = ctx.upstream.lock().unwrap().clone();
|
||||||
let (upstream_matched, upstream_detail) =
|
let (upstream_matched, upstream_detail) =
|
||||||
forward_query_for_diagnose(&domain_lower, upstream, ctx.timeout).await;
|
forward_query_for_diagnose(&domain_lower, &upstream, ctx.timeout).await;
|
||||||
steps.push(DiagnoseStep {
|
steps.push(DiagnoseStep {
|
||||||
source: "upstream".to_string(),
|
source: "upstream".to_string(),
|
||||||
matched: upstream_matched,
|
matched: upstream_matched,
|
||||||
@@ -373,7 +373,7 @@ async fn diagnose(
|
|||||||
|
|
||||||
async fn forward_query_for_diagnose(
|
async fn forward_query_for_diagnose(
|
||||||
domain: &str,
|
domain: &str,
|
||||||
upstream: std::net::SocketAddr,
|
upstream: &Upstream,
|
||||||
timeout: std::time::Duration,
|
timeout: std::time::Duration,
|
||||||
) -> (bool, String) {
|
) -> (bool, String) {
|
||||||
use crate::packet::DnsPacket;
|
use crate::packet::DnsPacket;
|
||||||
@@ -711,7 +711,11 @@ async fn create_service(
|
|||||||
}
|
}
|
||||||
|
|
||||||
let tld = &ctx.proxy_tld;
|
let tld = &ctx.proxy_tld;
|
||||||
|
let is_new = !ctx.services.lock().unwrap().has_name(&name);
|
||||||
ctx.services.lock().unwrap().insert(&name, req.target_port);
|
ctx.services.lock().unwrap().insert(&name, req.target_port);
|
||||||
|
if is_new {
|
||||||
|
crate::tls::regenerate_tls(&ctx);
|
||||||
|
}
|
||||||
|
|
||||||
let localhost = std::net::SocketAddr::from(([127, 0, 0, 1], req.target_port));
|
let localhost = std::net::SocketAddr::from(([127, 0, 0, 1], req.target_port));
|
||||||
let lan_addr =
|
let lan_addr =
|
||||||
@@ -740,8 +744,9 @@ async fn remove_service(State(ctx): State<Arc<ServerCtx>>, Path(name): Path<Stri
|
|||||||
if name.eq_ignore_ascii_case("numa") {
|
if name.eq_ignore_ascii_case("numa") {
|
||||||
return StatusCode::FORBIDDEN;
|
return StatusCode::FORBIDDEN;
|
||||||
}
|
}
|
||||||
let mut store = ctx.services.lock().unwrap();
|
let removed = ctx.services.lock().unwrap().remove(&name);
|
||||||
if store.remove(&name) {
|
if removed {
|
||||||
|
crate::tls::regenerate_tls(&ctx);
|
||||||
StatusCode::NO_CONTENT
|
StatusCode::NO_CONTENT
|
||||||
} else {
|
} else {
|
||||||
StatusCode::NOT_FOUND
|
StatusCode::NOT_FOUND
|
||||||
|
|||||||
@@ -21,6 +21,13 @@ impl BytePacketBuffer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn from_bytes(data: &[u8]) -> Self {
|
||||||
|
let mut buf = Self::new();
|
||||||
|
let len = data.len().min(BUF_SIZE);
|
||||||
|
buf.buf[..len].copy_from_slice(&data[..len]);
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
pub fn pos(&self) -> usize {
|
pub fn pos(&self) -> usize {
|
||||||
self.pos
|
self.pos
|
||||||
}
|
}
|
||||||
|
|||||||
15
src/ctx.rs
15
src/ctx.rs
@@ -3,14 +3,16 @@ use std::path::PathBuf;
|
|||||||
use std::sync::Mutex;
|
use std::sync::Mutex;
|
||||||
use std::time::{Duration, Instant, SystemTime};
|
use std::time::{Duration, Instant, SystemTime};
|
||||||
|
|
||||||
|
use arc_swap::ArcSwap;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
|
use rustls::ServerConfig;
|
||||||
use tokio::net::UdpSocket;
|
use tokio::net::UdpSocket;
|
||||||
|
|
||||||
use crate::blocklist::BlocklistStore;
|
use crate::blocklist::BlocklistStore;
|
||||||
use crate::buffer::BytePacketBuffer;
|
use crate::buffer::BytePacketBuffer;
|
||||||
use crate::cache::DnsCache;
|
use crate::cache::DnsCache;
|
||||||
use crate::config::ZoneMap;
|
use crate::config::ZoneMap;
|
||||||
use crate::forward::forward_query;
|
use crate::forward::{forward_query, Upstream};
|
||||||
use crate::header::ResultCode;
|
use crate::header::ResultCode;
|
||||||
use crate::lan::PeerStore;
|
use crate::lan::PeerStore;
|
||||||
use crate::override_store::OverrideStore;
|
use crate::override_store::OverrideStore;
|
||||||
@@ -33,7 +35,7 @@ pub struct ServerCtx {
|
|||||||
pub services: Mutex<ServiceStore>,
|
pub services: Mutex<ServiceStore>,
|
||||||
pub lan_peers: Mutex<PeerStore>,
|
pub lan_peers: Mutex<PeerStore>,
|
||||||
pub forwarding_rules: Vec<ForwardingRule>,
|
pub forwarding_rules: Vec<ForwardingRule>,
|
||||||
pub upstream: Mutex<SocketAddr>,
|
pub upstream: Mutex<Upstream>,
|
||||||
pub upstream_auto: bool,
|
pub upstream_auto: bool,
|
||||||
pub upstream_port: u16,
|
pub upstream_port: u16,
|
||||||
pub lan_ip: Mutex<std::net::Ipv4Addr>,
|
pub lan_ip: Mutex<std::net::Ipv4Addr>,
|
||||||
@@ -45,6 +47,7 @@ pub struct ServerCtx {
|
|||||||
pub config_found: bool,
|
pub config_found: bool,
|
||||||
pub config_dir: PathBuf,
|
pub config_dir: PathBuf,
|
||||||
pub data_dir: PathBuf,
|
pub data_dir: PathBuf,
|
||||||
|
pub tls_config: Option<ArcSwap<ServerConfig>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn handle_query(
|
pub async fn handle_query(
|
||||||
@@ -140,9 +143,11 @@ pub async fn handle_query(
|
|||||||
(resp, QueryPath::Cached)
|
(resp, QueryPath::Cached)
|
||||||
} else {
|
} else {
|
||||||
let upstream =
|
let upstream =
|
||||||
crate::system_dns::match_forwarding_rule(&qname, &ctx.forwarding_rules)
|
match crate::system_dns::match_forwarding_rule(&qname, &ctx.forwarding_rules) {
|
||||||
.unwrap_or_else(|| *ctx.upstream.lock().unwrap());
|
Some(addr) => Upstream::Udp(addr),
|
||||||
match forward_query(&query, upstream, ctx.timeout).await {
|
None => ctx.upstream.lock().unwrap().clone(),
|
||||||
|
};
|
||||||
|
match forward_query(&query, &upstream, ctx.timeout).await {
|
||||||
Ok(resp) => {
|
Ok(resp) => {
|
||||||
ctx.cache.lock().unwrap().insert(&qname, qtype, &resp);
|
ctx.cache.lock().unwrap().insert(&qname, qtype, &resp);
|
||||||
(resp, QueryPath::Forwarded)
|
(resp, QueryPath::Forwarded)
|
||||||
|
|||||||
211
src/forward.rs
211
src/forward.rs
@@ -1,3 +1,4 @@
|
|||||||
|
use std::fmt;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
@@ -8,7 +9,46 @@ use crate::buffer::BytePacketBuffer;
|
|||||||
use crate::packet::DnsPacket;
|
use crate::packet::DnsPacket;
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum Upstream {
|
||||||
|
Udp(SocketAddr),
|
||||||
|
Doh {
|
||||||
|
url: String,
|
||||||
|
client: reqwest::Client,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Upstream {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
match (self, other) {
|
||||||
|
(Self::Udp(a), Self::Udp(b)) => a == b,
|
||||||
|
(Self::Doh { url: a, .. }, Self::Doh { url: b, .. }) => a == b,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for Upstream {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Upstream::Udp(addr) => write!(f, "{}", addr),
|
||||||
|
Upstream::Doh { url, .. } => f.write_str(url),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn forward_query(
|
pub async fn forward_query(
|
||||||
|
query: &DnsPacket,
|
||||||
|
upstream: &Upstream,
|
||||||
|
timeout_duration: Duration,
|
||||||
|
) -> Result<DnsPacket> {
|
||||||
|
match upstream {
|
||||||
|
Upstream::Udp(addr) => forward_udp(query, *addr, timeout_duration).await,
|
||||||
|
Upstream::Doh { url, client } => forward_doh(query, url, client, timeout_duration).await,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn forward_udp(
|
||||||
query: &DnsPacket,
|
query: &DnsPacket,
|
||||||
upstream: SocketAddr,
|
upstream: SocketAddr,
|
||||||
timeout_duration: Duration,
|
timeout_duration: Duration,
|
||||||
@@ -33,3 +73,174 @@ pub async fn forward_query(
|
|||||||
|
|
||||||
DnsPacket::from_buffer(&mut recv_buffer)
|
DnsPacket::from_buffer(&mut recv_buffer)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn forward_doh(
|
||||||
|
query: &DnsPacket,
|
||||||
|
url: &str,
|
||||||
|
client: &reqwest::Client,
|
||||||
|
timeout_duration: Duration,
|
||||||
|
) -> Result<DnsPacket> {
|
||||||
|
let mut send_buffer = BytePacketBuffer::new();
|
||||||
|
query.write(&mut send_buffer)?;
|
||||||
|
|
||||||
|
let resp = timeout(
|
||||||
|
timeout_duration,
|
||||||
|
client
|
||||||
|
.post(url)
|
||||||
|
.header("content-type", "application/dns-message")
|
||||||
|
.header("accept", "application/dns-message")
|
||||||
|
.body(send_buffer.filled().to_vec())
|
||||||
|
.send(),
|
||||||
|
)
|
||||||
|
.await??
|
||||||
|
.error_for_status()?;
|
||||||
|
|
||||||
|
let bytes = resp.bytes().await?;
|
||||||
|
log::debug!("DoH response: {} bytes", bytes.len());
|
||||||
|
|
||||||
|
let mut recv_buffer = BytePacketBuffer::from_bytes(&bytes);
|
||||||
|
DnsPacket::from_buffer(&mut recv_buffer)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::future::IntoFuture;
|
||||||
|
|
||||||
|
use crate::header::ResultCode;
|
||||||
|
use crate::question::{DnsQuestion, QueryType};
|
||||||
|
use crate::record::DnsRecord;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn upstream_display_udp() {
|
||||||
|
let u = Upstream::Udp("9.9.9.9:53".parse().unwrap());
|
||||||
|
assert_eq!(u.to_string(), "9.9.9.9:53");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn upstream_display_doh() {
|
||||||
|
let u = Upstream::Doh {
|
||||||
|
url: "https://dns.quad9.net/dns-query".to_string(),
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
};
|
||||||
|
assert_eq!(u.to_string(), "https://dns.quad9.net/dns-query");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_query() -> DnsPacket {
|
||||||
|
let mut q = DnsPacket::new();
|
||||||
|
q.header.id = 0xABCD;
|
||||||
|
q.header.recursion_desired = true;
|
||||||
|
q.questions
|
||||||
|
.push(DnsQuestion::new("example.com".to_string(), QueryType::A));
|
||||||
|
q
|
||||||
|
}
|
||||||
|
|
||||||
|
fn make_response(query: &DnsPacket) -> DnsPacket {
|
||||||
|
let mut resp = DnsPacket::response_from(query, ResultCode::NOERROR);
|
||||||
|
resp.answers.push(DnsRecord::A {
|
||||||
|
domain: "example.com".to_string(),
|
||||||
|
addr: "93.184.216.34".parse().unwrap(),
|
||||||
|
ttl: 300,
|
||||||
|
});
|
||||||
|
resp
|
||||||
|
}
|
||||||
|
|
||||||
|
fn to_wire(pkt: &DnsPacket) -> Vec<u8> {
|
||||||
|
let mut buf = BytePacketBuffer::new();
|
||||||
|
pkt.write(&mut buf).unwrap();
|
||||||
|
buf.filled().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn doh_mock_server_resolves() {
|
||||||
|
let query = make_query();
|
||||||
|
let response_bytes = to_wire(&make_response(&query));
|
||||||
|
|
||||||
|
let app = axum::Router::new().route(
|
||||||
|
"/dns-query",
|
||||||
|
axum::routing::post(move || {
|
||||||
|
let body = response_bytes.clone();
|
||||||
|
async move {
|
||||||
|
(
|
||||||
|
[(axum::http::header::CONTENT_TYPE, "application/dns-message")],
|
||||||
|
body,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(axum::serve(listener, app).into_future());
|
||||||
|
|
||||||
|
let upstream = Upstream::Doh {
|
||||||
|
url: format!("http://{}/dns-query", addr),
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = forward_query(&query, &upstream, Duration::from_secs(2))
|
||||||
|
.await
|
||||||
|
.expect("DoH forward should succeed");
|
||||||
|
|
||||||
|
assert_eq!(result.header.id, 0xABCD);
|
||||||
|
assert!(result.header.response);
|
||||||
|
assert_eq!(result.header.rescode, ResultCode::NOERROR);
|
||||||
|
assert_eq!(result.answers.len(), 1);
|
||||||
|
match &result.answers[0] {
|
||||||
|
DnsRecord::A { domain, addr, ttl } => {
|
||||||
|
assert_eq!(domain, "example.com");
|
||||||
|
assert_eq!(
|
||||||
|
*addr,
|
||||||
|
"93.184.216.34".parse::<std::net::Ipv4Addr>().unwrap()
|
||||||
|
);
|
||||||
|
assert_eq!(*ttl, 300);
|
||||||
|
}
|
||||||
|
other => panic!("expected A record, got {:?}", other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn doh_http_error_propagates() {
|
||||||
|
let app = axum::Router::new().route(
|
||||||
|
"/dns-query",
|
||||||
|
axum::routing::post(|| async {
|
||||||
|
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, "bad")
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(axum::serve(listener, app).into_future());
|
||||||
|
|
||||||
|
let upstream = Upstream::Doh {
|
||||||
|
url: format!("http://{}/dns-query", addr),
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = forward_query(&make_query(), &upstream, Duration::from_secs(2)).await;
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn doh_timeout() {
|
||||||
|
let app = axum::Router::new().route(
|
||||||
|
"/dns-query",
|
||||||
|
axum::routing::post(|| async {
|
||||||
|
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||||
|
"never"
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let addr = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(axum::serve(listener, app).into_future());
|
||||||
|
|
||||||
|
let upstream = Upstream::Doh {
|
||||||
|
url: format!("http://{}/dns-query", addr),
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = forward_query(&make_query(), &upstream, Duration::from_millis(100)).await;
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
24
src/lan.rs
24
src/lan.rs
@@ -33,11 +33,18 @@ impl PeerStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update(&mut self, host: IpAddr, services: &[(String, u16)]) {
|
/// Returns true if a previously-unseen name was inserted.
|
||||||
|
pub fn update(&mut self, host: IpAddr, services: &[(String, u16)]) -> bool {
|
||||||
let now = Instant::now();
|
let now = Instant::now();
|
||||||
|
let mut changed = false;
|
||||||
for (name, port) in services {
|
for (name, port) in services {
|
||||||
self.peers.insert(name.to_lowercase(), (host, *port, now));
|
let key = name.to_lowercase();
|
||||||
|
if !self.peers.contains_key(&key) {
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
self.peers.insert(key, (host, *port, now));
|
||||||
}
|
}
|
||||||
|
changed
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn lookup(&mut self, name: &str) -> Option<(IpAddr, u16)> {
|
pub fn lookup(&mut self, name: &str) -> Option<(IpAddr, u16)> {
|
||||||
@@ -67,6 +74,13 @@ impl PeerStore {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn names(&mut self) -> Vec<String> {
|
||||||
|
let now = Instant::now();
|
||||||
|
self.peers
|
||||||
|
.retain(|_, (_, _, seen)| now.duration_since(*seen) < self.timeout);
|
||||||
|
self.peers.keys().cloned().collect()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn clear(&mut self) {
|
pub fn clear(&mut self) {
|
||||||
self.peers.clear();
|
self.peers.clear();
|
||||||
}
|
}
|
||||||
@@ -189,10 +203,14 @@ pub async fn start_lan_discovery(ctx: Arc<ServerCtx>, config: &LanConfig) {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if !ann.services.is_empty() {
|
if !ann.services.is_empty() {
|
||||||
ctx.lan_peers
|
let changed = ctx
|
||||||
|
.lan_peers
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.update(ann.peer_ip, &ann.services);
|
.update(ann.peer_ip, &ann.services);
|
||||||
|
if changed {
|
||||||
|
crate::tls::regenerate_tls(&ctx);
|
||||||
|
}
|
||||||
debug!(
|
debug!(
|
||||||
"LAN: {} services from {} (mDNS)",
|
"LAN: {} services from {} (mDNS)",
|
||||||
ann.services.len(),
|
ann.services.len(),
|
||||||
|
|||||||
86
src/main.rs
86
src/main.rs
@@ -2,6 +2,7 @@ use std::net::SocketAddr;
|
|||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use arc_swap::ArcSwap;
|
||||||
use log::{error, info};
|
use log::{error, info};
|
||||||
use tokio::net::UdpSocket;
|
use tokio::net::UdpSocket;
|
||||||
|
|
||||||
@@ -10,6 +11,7 @@ use numa::buffer::BytePacketBuffer;
|
|||||||
use numa::cache::DnsCache;
|
use numa::cache::DnsCache;
|
||||||
use numa::config::{build_zone_map, load_config, ConfigLoad};
|
use numa::config::{build_zone_map, load_config, ConfigLoad};
|
||||||
use numa::ctx::{handle_query, ServerCtx};
|
use numa::ctx::{handle_query, ServerCtx};
|
||||||
|
use numa::forward::Upstream;
|
||||||
use numa::override_store::OverrideStore;
|
use numa::override_store::OverrideStore;
|
||||||
use numa::query_log::QueryLog;
|
use numa::query_log::QueryLog;
|
||||||
use numa::service_store::ServiceStore;
|
use numa::service_store::ServiceStore;
|
||||||
@@ -110,13 +112,27 @@ async fn main() -> numa::Result<()> {
|
|||||||
.default_upstream
|
.default_upstream
|
||||||
.or_else(numa::system_dns::detect_dhcp_dns)
|
.or_else(numa::system_dns::detect_dhcp_dns)
|
||||||
.unwrap_or_else(|| {
|
.unwrap_or_else(|| {
|
||||||
info!("could not detect system DNS, falling back to 9.9.9.9 (Quad9)");
|
info!("could not detect system DNS, falling back to Quad9 DoH");
|
||||||
"9.9.9.9".to_string()
|
"https://dns.quad9.net/dns-query".to_string()
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
config.upstream.address.clone()
|
config.upstream.address.clone()
|
||||||
};
|
};
|
||||||
let upstream: SocketAddr = format!("{}:{}", upstream_addr, config.upstream.port).parse()?;
|
|
||||||
|
let upstream: Upstream = if upstream_addr.starts_with("https://") {
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.use_rustls_tls()
|
||||||
|
.build()
|
||||||
|
.unwrap_or_default();
|
||||||
|
Upstream::Doh {
|
||||||
|
url: upstream_addr,
|
||||||
|
client,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let addr: SocketAddr = format!("{}:{}", upstream_addr, config.upstream.port).parse()?;
|
||||||
|
Upstream::Udp(addr)
|
||||||
|
};
|
||||||
|
let upstream_label = upstream.to_string();
|
||||||
let api_port = config.server.api_port;
|
let api_port = config.server.api_port;
|
||||||
|
|
||||||
let mut blocklist = BlocklistStore::new();
|
let mut blocklist = BlocklistStore::new();
|
||||||
@@ -137,6 +153,20 @@ async fn main() -> numa::Result<()> {
|
|||||||
|
|
||||||
let forwarding_rules = system_dns.forwarding_rules;
|
let forwarding_rules = system_dns.forwarding_rules;
|
||||||
|
|
||||||
|
// Build initial TLS config before ServerCtx (so ArcSwap is ready at construction)
|
||||||
|
let initial_tls = if config.proxy.enabled && config.proxy.tls_port > 0 {
|
||||||
|
let service_names = service_store.names();
|
||||||
|
match numa::tls::build_tls_config(&config.proxy.tld, &service_names) {
|
||||||
|
Ok(tls_config) => Some(ArcSwap::from(tls_config)),
|
||||||
|
Err(e) => {
|
||||||
|
log::warn!("TLS setup failed, HTTPS proxy disabled: {}", e);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
let ctx = Arc::new(ServerCtx {
|
let ctx = Arc::new(ServerCtx {
|
||||||
socket: UdpSocket::bind(&config.server.bind_addr).await?,
|
socket: UdpSocket::bind(&config.server.bind_addr).await?,
|
||||||
zone_map: build_zone_map(&config.zones)?,
|
zone_map: build_zone_map(&config.zones)?,
|
||||||
@@ -168,6 +198,7 @@ async fn main() -> numa::Result<()> {
|
|||||||
config_found,
|
config_found,
|
||||||
config_dir: numa::config_dir(),
|
config_dir: numa::config_dir(),
|
||||||
data_dir: numa::data_dir(),
|
data_dir: numa::data_dir(),
|
||||||
|
tls_config: initial_tls,
|
||||||
});
|
});
|
||||||
|
|
||||||
let zone_count: usize = ctx.zone_map.values().map(|m| m.len()).sum();
|
let zone_count: usize = ctx.zone_map.values().map(|m| m.len()).sum();
|
||||||
@@ -201,7 +232,7 @@ async fn main() -> numa::Result<()> {
|
|||||||
let val_w = [
|
let val_w = [
|
||||||
config.server.bind_addr.len(),
|
config.server.bind_addr.len(),
|
||||||
api_url.len(),
|
api_url.len(),
|
||||||
upstream.to_string().len(),
|
upstream_label.len(),
|
||||||
config_label.len(),
|
config_label.len(),
|
||||||
data_label.len(),
|
data_label.len(),
|
||||||
services_label.len(),
|
services_label.len(),
|
||||||
@@ -245,7 +276,7 @@ async fn main() -> numa::Result<()> {
|
|||||||
row("DNS", g, &config.server.bind_addr);
|
row("DNS", g, &config.server.bind_addr);
|
||||||
row("API", g, &api_url);
|
row("API", g, &api_url);
|
||||||
row("Dashboard", g, &api_url);
|
row("Dashboard", g, &api_url);
|
||||||
row("Upstream", g, &upstream.to_string());
|
row("Upstream", g, &upstream_label);
|
||||||
row("Zones", g, &format!("{} records", zone_count));
|
row("Zones", g, &format!("{} records", zone_count));
|
||||||
row(
|
row(
|
||||||
"Cache",
|
"Cache",
|
||||||
@@ -282,7 +313,7 @@ async fn main() -> numa::Result<()> {
|
|||||||
|
|
||||||
info!(
|
info!(
|
||||||
"numa listening on {}, upstream {}, {} zone records, cache max {}, API on port {}",
|
"numa listening on {}, upstream {}, {} zone records, cache max {}, API on port {}",
|
||||||
config.server.bind_addr, upstream, zone_count, config.cache.max_entries, api_port,
|
config.server.bind_addr, upstream_label, zone_count, config.cache.max_entries, api_port,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Download blocklists on startup
|
// Download blocklists on startup
|
||||||
@@ -336,27 +367,12 @@ async fn main() -> numa::Result<()> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Spawn HTTPS reverse proxy with TLS termination
|
// Spawn HTTPS reverse proxy with TLS termination
|
||||||
if config.proxy.enabled && config.proxy.tls_port > 0 {
|
if config.proxy.enabled && config.proxy.tls_port > 0 && ctx.tls_config.is_some() {
|
||||||
let service_names: Vec<String> = ctx
|
let proxy_ctx = Arc::clone(&ctx);
|
||||||
.services
|
let tls_port = config.proxy.tls_port;
|
||||||
.lock()
|
tokio::spawn(async move {
|
||||||
.unwrap()
|
numa::proxy::start_proxy_tls(proxy_ctx, tls_port, proxy_bind).await;
|
||||||
.list()
|
});
|
||||||
.iter()
|
|
||||||
.map(|e| e.name.clone())
|
|
||||||
.collect();
|
|
||||||
match numa::tls::build_tls_config(&config.proxy.tld, &service_names) {
|
|
||||||
Ok(tls_config) => {
|
|
||||||
let proxy_ctx = Arc::clone(&ctx);
|
|
||||||
let tls_port = config.proxy.tls_port;
|
|
||||||
tokio::spawn(async move {
|
|
||||||
numa::proxy::start_proxy_tls(proxy_ctx, tls_port, proxy_bind, tls_config).await;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
log::warn!("TLS setup failed, HTTPS proxy disabled: {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Spawn network change watcher (upstream re-detection, LAN IP update, peer flush)
|
// Spawn network change watcher (upstream re-detection, LAN IP update, peer flush)
|
||||||
@@ -412,20 +428,24 @@ async fn network_watch_loop(ctx: Arc<numa::ctx::ServerCtx>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check upstream change every 30s or immediately on LAN IP change
|
// Re-detect upstream every 30s or on LAN IP change (UDP only —
|
||||||
// (heavier — spawns scutil/ipconfig, only when auto-detected)
|
// DoH upstreams are explicitly configured via URL, not auto-detected)
|
||||||
if ctx.upstream_auto && (changed || tick.is_multiple_of(6)) {
|
if ctx.upstream_auto
|
||||||
|
&& matches!(*ctx.upstream.lock().unwrap(), Upstream::Udp(_))
|
||||||
|
&& (changed || tick.is_multiple_of(6))
|
||||||
|
{
|
||||||
let dns_info = numa::system_dns::discover_system_dns();
|
let dns_info = numa::system_dns::discover_system_dns();
|
||||||
let new_addr = dns_info
|
let new_addr = dns_info
|
||||||
.default_upstream
|
.default_upstream
|
||||||
.or_else(numa::system_dns::detect_dhcp_dns)
|
.or_else(numa::system_dns::detect_dhcp_dns)
|
||||||
.unwrap_or_else(|| "9.9.9.9".to_string());
|
.unwrap_or_else(|| "9.9.9.9".to_string());
|
||||||
if let Ok(new_upstream) =
|
if let Ok(new_sock) =
|
||||||
format!("{}:{}", new_addr, ctx.upstream_port).parse::<SocketAddr>()
|
format!("{}:{}", new_addr, ctx.upstream_port).parse::<SocketAddr>()
|
||||||
{
|
{
|
||||||
|
let new_upstream = Upstream::Udp(new_sock);
|
||||||
let mut upstream = ctx.upstream.lock().unwrap();
|
let mut upstream = ctx.upstream.lock().unwrap();
|
||||||
if new_upstream != *upstream {
|
if *upstream != new_upstream {
|
||||||
info!("upstream changed: {} → {}", *upstream, new_upstream);
|
info!("upstream changed: {} → {}", upstream, new_upstream);
|
||||||
*upstream = new_upstream;
|
*upstream = new_upstream;
|
||||||
changed = true;
|
changed = true;
|
||||||
}
|
}
|
||||||
|
|||||||
21
src/proxy.rs
21
src/proxy.rs
@@ -11,7 +11,6 @@ use hyper::StatusCode;
|
|||||||
use hyper_util::client::legacy::Client;
|
use hyper_util::client::legacy::Client;
|
||||||
use hyper_util::rt::TokioExecutor;
|
use hyper_util::rt::TokioExecutor;
|
||||||
use log::{debug, error, info, warn};
|
use log::{debug, error, info, warn};
|
||||||
use rustls::ServerConfig;
|
|
||||||
use tokio::io::copy_bidirectional;
|
use tokio::io::copy_bidirectional;
|
||||||
use tokio_rustls::TlsAcceptor;
|
use tokio_rustls::TlsAcceptor;
|
||||||
|
|
||||||
@@ -50,12 +49,7 @@ pub async fn start_proxy(ctx: Arc<ServerCtx>, port: u16, bind_addr: Ipv4Addr) {
|
|||||||
axum::serve(listener, app).await.unwrap();
|
axum::serve(listener, app).await.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn start_proxy_tls(
|
pub async fn start_proxy_tls(ctx: Arc<ServerCtx>, port: u16, bind_addr: Ipv4Addr) {
|
||||||
ctx: Arc<ServerCtx>,
|
|
||||||
port: u16,
|
|
||||||
bind_addr: Ipv4Addr,
|
|
||||||
tls_config: Arc<ServerConfig>,
|
|
||||||
) {
|
|
||||||
let addr: SocketAddr = (bind_addr, port).into();
|
let addr: SocketAddr = (bind_addr, port).into();
|
||||||
let listener = match tokio::net::TcpListener::bind(addr).await {
|
let listener = match tokio::net::TcpListener::bind(addr).await {
|
||||||
Ok(l) => l,
|
Ok(l) => l,
|
||||||
@@ -69,11 +63,17 @@ pub async fn start_proxy_tls(
|
|||||||
};
|
};
|
||||||
info!("HTTPS proxy listening on {}", addr);
|
info!("HTTPS proxy listening on {}", addr);
|
||||||
|
|
||||||
let acceptor = TlsAcceptor::from(tls_config);
|
if ctx.tls_config.is_none() {
|
||||||
|
warn!("proxy: no TLS config — HTTPS proxy disabled");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
let client: HttpClient = Client::builder(TokioExecutor::new())
|
let client: HttpClient = Client::builder(TokioExecutor::new())
|
||||||
.http1_preserve_header_case(true)
|
.http1_preserve_header_case(true)
|
||||||
.build_http();
|
.build_http();
|
||||||
|
|
||||||
|
// Hold a separate Arc so we can access tls_config after ctx moves into ProxyState
|
||||||
|
let tls_holder = Arc::clone(&ctx);
|
||||||
let state = ProxyState { ctx, client };
|
let state = ProxyState { ctx, client };
|
||||||
|
|
||||||
let app = Router::new().fallback(any(proxy_handler)).with_state(state);
|
let app = Router::new().fallback(any(proxy_handler)).with_state(state);
|
||||||
@@ -87,7 +87,10 @@ pub async fn start_proxy_tls(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let acceptor = acceptor.clone();
|
// Load the latest TLS config on each connection (picks up new service certs)
|
||||||
|
// unwrap safe: guarded by is_none() check above
|
||||||
|
let acceptor =
|
||||||
|
TlsAcceptor::from(Arc::clone(&*tls_holder.tls_config.as_ref().unwrap().load()));
|
||||||
let app = app.clone();
|
let app = app.clone();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
|
|||||||
@@ -154,6 +154,15 @@ impl ServiceStore {
|
|||||||
entries
|
entries
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn names(&self) -> Vec<String> {
|
||||||
|
self.entries.keys().cloned().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true if the name is new (not already registered).
|
||||||
|
pub fn has_name(&self, name: &str) -> bool {
|
||||||
|
self.entries.contains_key(&name.to_lowercase())
|
||||||
|
}
|
||||||
|
|
||||||
/// Load user-defined services from ~/.config/numa/services.json
|
/// Load user-defined services from ~/.config/numa/services.json
|
||||||
pub fn load_persisted(&mut self) {
|
pub fn load_persisted(&mut self) {
|
||||||
if !self.persist_path.exists() {
|
if !self.persist_path.exists() {
|
||||||
|
|||||||
23
src/tls.rs
23
src/tls.rs
@@ -1,7 +1,10 @@
|
|||||||
|
use std::collections::HashSet;
|
||||||
use std::path::Path;
|
use std::path::Path;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use log::{info, warn};
|
use log::{info, warn};
|
||||||
|
|
||||||
|
use crate::ctx::ServerCtx;
|
||||||
use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType};
|
use rcgen::{BasicConstraints, CertificateParams, DnType, IsCa, KeyPair, KeyUsagePurpose, SanType};
|
||||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||||
use rustls::ServerConfig;
|
use rustls::ServerConfig;
|
||||||
@@ -10,6 +13,26 @@ use time::{Duration, OffsetDateTime};
|
|||||||
const CA_VALIDITY_DAYS: i64 = 3650; // 10 years
|
const CA_VALIDITY_DAYS: i64 = 3650; // 10 years
|
||||||
const CERT_VALIDITY_DAYS: i64 = 365; // 1 year
|
const CERT_VALIDITY_DAYS: i64 = 365; // 1 year
|
||||||
|
|
||||||
|
/// Collect all service + LAN peer names and regenerate the TLS cert.
|
||||||
|
pub fn regenerate_tls(ctx: &ServerCtx) {
|
||||||
|
let tls = match &ctx.tls_config {
|
||||||
|
Some(t) => t,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut names: HashSet<String> = ctx.services.lock().unwrap().names().into_iter().collect();
|
||||||
|
names.extend(ctx.lan_peers.lock().unwrap().names());
|
||||||
|
let names: Vec<String> = names.into_iter().collect();
|
||||||
|
|
||||||
|
match build_tls_config(&ctx.proxy_tld, &names) {
|
||||||
|
Ok(new_config) => {
|
||||||
|
tls.store(new_config);
|
||||||
|
info!("TLS cert regenerated for {} services", names.len());
|
||||||
|
}
|
||||||
|
Err(e) => warn!("TLS regeneration failed: {}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Build a TLS config with a cert covering all provided service names.
|
/// Build a TLS config with a cert covering all provided service names.
|
||||||
/// Wildcards under single-label TLDs (*.numa) are rejected by browsers,
|
/// Wildcards under single-label TLDs (*.numa) are rejected by browsers,
|
||||||
/// so we list each service explicitly as a SAN.
|
/// so we list each service explicitly as a SAN.
|
||||||
|
|||||||
Reference in New Issue
Block a user