From 0f1b6e09f331e3260c10d4dcbba6f686020559de Mon Sep 17 00:00:00 2001 From: "Mr. Juan" <240553480+sovsender@users.noreply.github.com> Date: Fri, 6 Nov 2026 12:29:29 -0500 Subject: [PATCH 01/12] feat(start-wrt): join another Wi-Fi network as a WAN uplink A Wi-Fi uplink set up in LuCI worked, but StartWRT did not know about it: turning a band off on the Wi-Fi page dropped the uplink, and nothing let a user set one up from StartWRT itself. Add a Wireless WAN page under Internet and a `wwan` RPC namespace (get, scan, connect, priority-set, disconnect). StartWRT owns the `wwan` sections of `wireless` (a client-mode wifi-iface) and `network` (a DHCP interface) and adds `wwan` to the `wan` firewall zone, so profiles routed through the WAN, published ports and remote access use it without changes of their own. The priority is the two interfaces' route metrics, and netifd uses the lower one while both have a default route. - `system::active_uplink` reads `network.interface dump` and picks the uplink that carries the default route. The WAN address readers behind published ports, PCP/UPnP and remote access follow it, and their hotplug hooks fire on `wwan` and on `ifdown`, since the remaining uplink raises no `ifup` when the other drops. - The WAN DNS mode writes `peerdns` on `wwan` too, through a partial typed section, so custom DNS does not pick up the upstream network's servers. - `wifi.set` refuses to turn off a radio an enabled client-mode interface uses, whoever configured it (`WifiRadioCarriesUplink`). A client interface StartWRT did not create is reported as unmanaged and never written. - Scans pass the radio name to `ubus call iwinfo scan`; the pinned iwinfo resolves it to one of the radio's interfaces or a temporary one. OpenWrt 25.12's hostapd stops a radio's access points while wpa_supplicant on that radio is scanning, authenticating or disconnected, and starts them on the upstream channel once it associates. The join dialog, the Wi-Fi page, the help and the book say so. Co-Authored-By: Claude Opus 5.5 --- projects/start-wrt/API_CONTRACT.md | 118 +- projects/start-wrt/README.md | 18 +- projects/start-wrt/backend/ARCHITECTURE.md | 13 +- projects/start-wrt/backend/ctrl/src/error.rs | 6 + projects/start-wrt/backend/ctrl/src/lib.rs | 2 + projects/start-wrt/backend/ctrl/src/system.rs | 176 ++- projects/start-wrt/backend/ctrl/src/wan.rs | 107 +- projects/start-wrt/backend/ctrl/src/wifi.rs | 121 +- projects/start-wrt/backend/ctrl/src/wwan.rs | 1243 +++++++++++++++++ .../backend/hotplug/99-startwrt-port-control | 4 +- .../hotplug/99-startwrt-published-ports | 2 +- .../backend/hotplug/99-startwrt-remote-access | 2 +- .../minor-added-wireless-wan.de_DE.md | 1 + .../minor-added-wireless-wan.es_ES.md | 1 + .../minor-added-wireless-wan.fr_FR.md | 1 + .../changelog/minor-added-wireless-wan.md | 5 + .../minor-added-wireless-wan.pl_PL.md | 1 + projects/start-wrt/docs/src/README.md | 1 + projects/start-wrt/docs/src/SUMMARY.md | 1 + projects/start-wrt/docs/src/overview.md | 1 + projects/start-wrt/docs/src/wifi-schedules.md | 2 +- projects/start-wrt/docs/src/wifi.md | 2 +- projects/start-wrt/docs/src/wireless-wan.md | 40 + projects/start-wrt/web/src/app/app.routes.ts | 4 + .../start-wrt/web/src/app/components/nav.ts | 5 + .../start-wrt/web/src/app/help/content/de.ts | 18 + .../start-wrt/web/src/app/help/content/en.ts | 18 + .../start-wrt/web/src/app/help/content/es.ts | 18 + .../start-wrt/web/src/app/help/content/fr.ts | 18 + .../start-wrt/web/src/app/help/content/pl.ts | 18 + .../web/src/app/i18n/dictionaries/de.ts | 35 + .../web/src/app/i18n/dictionaries/en.ts | 35 + .../web/src/app/i18n/dictionaries/es.ts | 35 + .../web/src/app/i18n/dictionaries/fr.ts | 35 + .../web/src/app/i18n/dictionaries/pl.ts | 35 + .../app/routes/wifi/routes/settings/index.ts | 33 + .../web/src/app/routes/wwan/dialog.ts | 213 +++ .../web/src/app/routes/wwan/index.ts | 299 ++++ .../web/src/app/routes/wwan/service.ts | 57 + .../web/src/app/routes/wwan/table.ts | 82 ++ .../web/src/app/routes/wwan/utils.ts | 21 + .../web/src/app/services/api/api.service.ts | 19 + .../src/app/services/api/bindings.schemas.ts | 312 +++++ .../web/src/app/services/api/bindings.ts | 26 + .../src/app/services/api/live-api.service.ts | 25 + .../src/app/services/api/mock-api.service.ts | 110 ++ 46 files changed, 3262 insertions(+), 77 deletions(-) create mode 100644 projects/start-wrt/backend/ctrl/src/wwan.rs create mode 100644 projects/start-wrt/changelog/minor-added-wireless-wan.de_DE.md create mode 100644 projects/start-wrt/changelog/minor-added-wireless-wan.es_ES.md create mode 100644 projects/start-wrt/changelog/minor-added-wireless-wan.fr_FR.md create mode 100644 projects/start-wrt/changelog/minor-added-wireless-wan.md create mode 100644 projects/start-wrt/changelog/minor-added-wireless-wan.pl_PL.md create mode 100644 projects/start-wrt/docs/src/wireless-wan.md create mode 100644 projects/start-wrt/web/src/app/routes/wwan/dialog.ts create mode 100644 projects/start-wrt/web/src/app/routes/wwan/index.ts create mode 100644 projects/start-wrt/web/src/app/routes/wwan/service.ts create mode 100644 projects/start-wrt/web/src/app/routes/wwan/table.ts create mode 100644 projects/start-wrt/web/src/app/routes/wwan/utils.ts diff --git a/projects/start-wrt/API_CONTRACT.md b/projects/start-wrt/API_CONTRACT.md index 8bee312a4f..47cb949e2f 100644 --- a/projects/start-wrt/API_CONTRACT.md +++ b/projects/start-wrt/API_CONTRACT.md @@ -587,7 +587,7 @@ struct WanDnsSetRequest { } // Response: null // Backend: stores custom servers in the `startwrt` config (`system_dns` -// section), sets `peerdns` on wan/wan6 (0 for Custom, 1 for Isp), rewrites +// section), sets `peerdns` on wan/wan6/wwan (0 for Custom, 1 for Isp), rewrites // per-profile DNS forwarding (dnsmasq + firewall DNAT), regenerates the // SmartDNS config, then runs the full reload_system() (network + smartdns + // firewall + dnsmasq) @@ -1753,6 +1753,9 @@ struct WifiSetResult { // (`autoWidths` for "auto"), or when the radio's PHY mode cannot express the // width (HT stops at 40 MHz). // A call that changes `country` instead rejects any width above 80 MHz. +// Turning off a radio that an enabled client-mode `wifi-iface` uses, whoever +// configured it, is rejected with `WifiRadioCarriesUplink` (1027), by a preview +// too. ``` ### `wifi.blackout-get` @@ -2329,6 +2332,112 @@ struct InjectedDnsRecord { --- +## 18. Wireless WAN + +The router as a Wi-Fi client of another network. StartWRT owns the `wwan` +sections of `wireless` and `network`; the `wwan` interface is a member of the +`wan` firewall zone. A client-mode `wifi-iface` under another name (one set up +in LuCI) is reported in `unmanaged` and never written. + +### `wwan.get` + +```rust +// Request: {} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +enum WwanSecurity { Open, Wpa2, Wpa2Wpa3, Wpa3 } // "open" | "wpa2" | "wpa2Wpa3" | "wpa3" + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +enum WwanPriority { + /// Used while the WAN port has no connection. + Backup, + /// Used while connected; the WAN port takes over when it drops. + Preferred, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct WwanResponse { + /// Every `wifi-device`, e.g. { radio: "radio0", band: "2g", enabled: true }. + radios: Vec, + uplink: Option, // { radio, band, ssid, security, priority } + /// Absent off the router and while there is no uplink. + state: Option, // { associated, address, signal (dBm), channel, active } + /// Client-mode Wi-Fi interfaces StartWRT did not create, by section name. + unmanaged: Vec, +} +// Backend: `state.active` is true while `wwan` carries the default route +// (`system::active_uplink`, from `network.interface dump`). The priority reads +// back from the two interfaces' route metrics. +``` + +### `wwan.scan` + +```rust +#[derive(Deserialize)] +struct WwanScanRequest { radio: String } + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct WwanNetwork { + ssid: String, // empty for a hidden network + bssid: String, + channel: Option, + signal: Option, // dBm + /// None for a network StartWRT cannot join (WPA Enterprise, OWE, WEP, WPA1). + security: Option, +} +// Response: Vec, one entry per network name (strongest access +// point), hidden networks one per access point, strongest first. +// Backend: `ubus call iwinfo scan {"device": }`; iwinfo scans on one of +// the radio's interfaces or a temporary one. A radio that is off or missing is +// rejected with `WifiRadioUnavailable` (1029). +``` + +### `wwan.connect` + +```rust +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct WwanConnectRequest { + radio: String, + ssid: String, // 1–32 bytes + security: WwanSecurity, + password: Option, // 8–63 characters; ignored for Open + priority: WwanPriority, +} +// Response: null +// Backend: replaces any `wwan` sections with a client-mode `wifi-iface 'wwan'` +// (`network 'wwan'`) and a DHCP `interface 'wwan'`, adds `wwan` to the `wan` +// zone, and writes route metrics: 10 on the preferred uplink, 20 on the other. +// `peerdns '0'` follows a custom WAN DNS setting. Rejects an off or missing +// radio (`WifiRadioUnavailable`), a bad name or password (`InvalidValue`), and +// an unmanaged client interface (`WifiUplinkConfiguredElsewhere`, 1028), writing +// nothing. Then reload_system(). +``` + +### `wwan.priority-set` + +```rust +#[derive(Deserialize)] +struct WwanPrioritySetRequest { priority: WwanPriority } +// Response: null +// Backend: rewrites the two route metrics; `NotFound` without an uplink. +``` + +### `wwan.disconnect` + +```rust +// Request: {} +// Response: null +// Backend: deletes the `wwan` sections, takes `wwan` out of the `wan` zone and +// clears `network.wan.metric`; `NotFound` without an uplink. +``` + +--- + ## HTTP Routes Every RPC method above is a JSON-RPC 2.0 call to a single endpoint: **`POST /rpc/v1`**. @@ -2381,6 +2490,11 @@ The daemon (`backend/ctrl/src/bins/daemon.rs`) also serves: | `wan.dns-set` | WAN | | | `wan.ddns-get` | WAN | | | `wan.ddns-set` | WAN | | +| `wwan.get` | Wireless WAN | | +| `wwan.scan` | Wireless WAN | | +| `wwan.connect` | Wireless WAN | | +| `wwan.priority-set` | Wireless WAN | | +| `wwan.disconnect` | Wireless WAN | | | `lan.ipv4-get` | LAN | | | `lan.ipv4-set` | LAN | | | `lan.ipv6-get` | LAN | | @@ -2440,7 +2554,7 @@ The daemon (`backend/ctrl/src/bins/daemon.rs`) also serves: | `diagnostics.create` | Diagnostics | | | `dns.injected-list` | DNS Injection | | -**Totals:** 84 RPC methods across 17 categories, plus the HTTP/WebSocket routes +**Totals:** 89 RPC methods across 18 categories, plus the HTTP/WebSocket routes table above and the deprecated generic endpoints below. --- diff --git a/projects/start-wrt/README.md b/projects/start-wrt/README.md index b3f56ec17d..31b55cbacc 100644 --- a/projects/start-wrt/README.md +++ b/projects/start-wrt/README.md @@ -42,6 +42,10 @@ Optionally disable WiFi on a schedule — for example, 10pm to 7am — to preven Keep a domain name pointed at your WAN address through a dynamic DNS provider: DynDNS, No-IP, Cloudflare, DuckDNS, or FreeDNS. +### Wireless WAN + +Join another Wi-Fi network as the router's Internet uplink, as a backup to the WAN port or in its place. + ### Published Ports Forward ports from the Internet to specific devices on the LAN, with per-rule controls for protocol, IP version, source filtering, and external port mapping. @@ -62,13 +66,13 @@ The StartWRT web interface is a single-page application that communicates with t The interface is organized around the router's feature areas: -| Section | Routes | Description | -| --------------------- | -------------------------------------------- | ------------------------------------------------------------- | -| **Internet** | WAN Settings, Published Ports, Outbound VPNs | External connectivity, port forwarding, VPN clients | -| **Network** | LAN Settings, Devices | Local network configuration and device management | -| **Security Profiles** | Profiles | Create and manage access control profiles | -| **Points of Entry** | Ethernet, Wi-Fi, Inbound VPNs | How devices join the network and get profiled | -| **System** | Settings | General, password, SSH keys, activity, logs, backup, advanced | +| Section | Routes | Description | +| --------------------- | ---------------------------------------------------------- | ----------------------------------------------------------------- | +| **Internet** | WAN Settings, Wireless WAN, Published Ports, Outbound VPNs | External connectivity, Wi-Fi uplink, port forwarding, VPN clients | +| **Network** | LAN Settings, Devices | Local network configuration and device management | +| **Security Profiles** | Profiles | Create and manage access control profiles | +| **Points of Entry** | Ethernet, Wi-Fi, Inbound VPNs | How devices join the network and get profiled | +| **System** | Settings | General, password, SSH keys, activity, logs, backup, advanced | ## Documentation diff --git a/projects/start-wrt/backend/ARCHITECTURE.md b/projects/start-wrt/backend/ARCHITECTURE.md index 6651c519c3..e9fa3a9648 100644 --- a/projects/start-wrt/backend/ARCHITECTURE.md +++ b/projects/start-wrt/backend/ARCHITECTURE.md @@ -107,6 +107,11 @@ dns wan # WAN IPv4/IPv6, MAC, DNS, DDNS config +wwan # Wi-Fi uplink (Wireless WAN) + ├─ get / scan + ├─ connect / disconnect + └─ priority-set + lan # LAN IPv4/IPv6 config published-ports # Port forwarding rules @@ -154,6 +159,12 @@ Manages WiFi blackout schedules: every Wi-Fi reload re-applies the state for the Creates `WifiStation` (password entries) and `WifiVlan` (VLAN mapping) sections in the `wireless` UCI config. +### wwan.rs — Wireless WAN + +Joins another Wi-Fi network as an uplink. It owns the `wwan` sections of `wireless` (a client-mode `wifi-iface`) and `network` (a DHCP interface), and adds `wwan` to the `wan` firewall zone, so profiles routed through the WAN, published ports and remote access treat it as the WAN. The priority is the two interfaces' route `metric`: netifd uses the lower one while both have a default route. `system::active_uplink` reports which one carries traffic, and the WAN address readers follow it. + +A client-mode interface on a radio ties that radio's access points to it: hostapd starts them on the upstream network's channel once wpa_supplicant associates, and stops them while it is scanning, authenticating or disconnected. `wifi.set` refuses to turn off a radio that carries one, whoever configured it. + ### ethernet.rs — Ethernet Port Assignment Maps physical ports to profiles via bridge VLAN assignments on the LAN bridge (`br-lan`). Also manages WAN port designation (which port is the uplink). Reads/writes `NetworkBridgeVlan` and `NetworkVlanPort` in the `network` UCI config. @@ -305,7 +316,7 @@ Shared, OpenWrt-native typed sections live in `uciedit/src/openwrt.rs`; feature- - Config errors: `InterfaceNameConflict`, `DuplicateVlanTag`, `DuplicatePassword`, `DuplicatePasswordLabel`, `DuplicateFullname` - Profile errors: `MissingProfile`, `CorruptedProfile`, `LanOwnerExists`, `CannotDeleteLanOwner` - Infrastructure errors: `MissingLanBridge`, `MissingWanInterface`, `MissingLanInterface`, `MissingFirewallZone` -- WiFi errors: `CorruptedWifi`, `UnnamedWirelessInterface`, `UnnamedWirelessDevice` +- WiFi errors: `CorruptedWifi`, `UnnamedWirelessInterface`, `UnnamedWirelessDevice`, `WifiRadioCarriesUplink`, `WifiUplinkConfiguredElsewhere`, `WifiRadioUnavailable` - VPN errors: `VpnHasDependents`, `VpnChainCycle`, `VpnPeersWouldBreak`, `VpnDisabled` - Validation: `InvalidValue`, `WanPortWithProfile`, `DhcpStaticHostsInSubnet`, `SubnetCollision`, `MissingDeviceAddress`, `PublishedPortsUseIpv6` - UCI errors: `UciEdit` (any `uciedit` parse, I/O, or write-conflict failure, and failed `uci` CLI calls) diff --git a/projects/start-wrt/backend/ctrl/src/error.rs b/projects/start-wrt/backend/ctrl/src/error.rs index 2ede0f2228..b20a505b95 100644 --- a/projects/start-wrt/backend/ctrl/src/error.rs +++ b/projects/start-wrt/backend/ctrl/src/error.rs @@ -62,6 +62,9 @@ pub enum ErrorKind { SubnetCollision = 1024, PublishedPortsUseIpv6 = 1025, VpnDisabled = 1026, + WifiRadioCarriesUplink = 1027, + WifiUplinkConfiguredElsewhere = 1028, + WifiRadioUnavailable = 1029, } impl From for startos::Error { @@ -132,6 +135,9 @@ impl ErrorKind { SubnetCollision => "Subnet Collision", PublishedPortsUseIpv6 => "Published Ports Use IPv6", VpnDisabled => "Outbound VPN Disabled", + WifiRadioCarriesUplink => "Radio Carries Wi-Fi Uplink", + WifiUplinkConfiguredElsewhere => "Wi-Fi Uplink Configured Elsewhere", + WifiRadioUnavailable => "Wi-Fi Radio Unavailable", } } } diff --git a/projects/start-wrt/backend/ctrl/src/lib.rs b/projects/start-wrt/backend/ctrl/src/lib.rs index 9393ba3c98..c7457fa66a 100644 --- a/projects/start-wrt/backend/ctrl/src/lib.rs +++ b/projects/start-wrt/backend/ctrl/src/lib.rs @@ -53,6 +53,7 @@ pub mod vpn_server; pub mod wan; pub mod wg; pub mod wifi; +pub mod wwan; use std::io::IsTerminal; use std::ops::Deref; @@ -414,6 +415,7 @@ pub fn main_api() -> ParentHandler { .subcommand("devices", devices::devices::()) .subcommand("dns", dns_inject::dns::()) .subcommand("wan", wan::wan::()) + .subcommand("wwan", wwan::wwan::()) .subcommand("lan", lan::lan::()) .subcommand("published-ports", published_ports::published_ports::()) .subcommand("ssh-keys", ssh_keys::ssh_keys::()) diff --git a/projects/start-wrt/backend/ctrl/src/system.rs b/projects/start-wrt/backend/ctrl/src/system.rs index 624b85a1a6..2949f9c551 100644 --- a/projects/start-wrt/backend/ctrl/src/system.rs +++ b/projects/start-wrt/backend/ctrl/src/system.rs @@ -229,54 +229,96 @@ pub(crate) fn addr_in_prefix(addr: Ipv6Addr, prefix: Ipv6Addr, prefix_len: u8) - (u128::from(addr) & mask) == (u128::from(prefix) & mask) } -pub(crate) async fn get_wan_ipv4() -> Result, Error> { - let stdout = match tokio::process::Command::new("ubus") - .args(["call", "network.interface.wan", "status"]) +const UPLINK_INTERFACES: [&str; 2] = [crate::wan::WAN_INTERFACE, crate::wan::WWAN_INTERFACE]; + +/// The uplink in a `network.interface dump` that carries the default route, +/// lowest metric first. Falls back to `wan` while neither has one. +fn uplink_status(dump: &serde_json::Value) -> Option<&serde_json::Value> { + let uplinks: Vec<&serde_json::Value> = dump + .get("interface")? + .as_array()? + .iter() + .filter(|i| { + i.get("interface") + .and_then(|v| v.as_str()) + .is_some_and(|name| UPLINK_INTERFACES.contains(&name)) + }) + .collect(); + let has_default_route = |i: &&&serde_json::Value| { + i.get("up").and_then(|v| v.as_bool()) == Some(true) + && i.get("route") + .and_then(|r| r.as_array()) + .is_some_and(|routes| { + routes.iter().any(|r| { + r.get("target").and_then(|t| t.as_str()) == Some("0.0.0.0") + && r.get("mask").and_then(|m| m.as_u64()) == Some(0) + }) + }) + }; + uplinks + .iter() + .filter(has_default_route) + .min_by_key(|i| i.get("metric").and_then(|m| m.as_u64()).unwrap_or(0)) + .or_else(|| { + uplinks.iter().find(|i| { + i.get("interface").and_then(|v| v.as_str()) == Some(crate::wan::WAN_INTERFACE) + }) + }) + .copied() +} + +fn uplink_ipv4_addrs(dump: &serde_json::Value) -> Vec { + uplink_status(dump) + .and_then(|i| i.get("ipv4-address")?.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|e| e.get("address")?.as_str()?.parse().ok()) + .collect() + }) + .unwrap_or_default() +} + +async fn interface_dump() -> Option { + let out = tokio::process::Command::new("ubus") + .args(["call", "network.interface", "dump"]) .invoke(ErrorKind::Network.into()) .await - { - Ok(out) => out, - Err(_) => return Ok(None), - }; - let json: serde_json::Value = match serde_json::from_slice(&stdout) { - Ok(v) => v, - Err(_) => return Ok(None), - }; - let addr_str = json - .pointer("/ipv4-address/0/address") - .and_then(|v| v.as_str()); - match addr_str { - Some(s) => Ok(s.parse().ok()), - None => Ok(None), - } + .ok()?; + serde_json::from_slice(&out).ok() } -/// Every IPv4 address on the `wan` interface, in ubus order. Empty when the -/// interface is down or ubus is unavailable. +/// The interface carrying the router's Internet traffic: `wan` or `wwan`. +pub(crate) async fn active_uplink() -> Option { + let dump = interface_dump().await?; + uplink_status(&dump)? + .get("interface")? + .as_str() + .map(String::from) +} + +pub(crate) async fn get_wan_ipv4() -> Result, Error> { + Ok(interface_dump() + .await + .and_then(|dump| uplink_ipv4_addrs(&dump).into_iter().next())) +} + +/// Every IPv4 address on the active uplink, in ubus order. Empty when it is +/// down or ubus is unavailable. pub(crate) fn wan_ipv4_addrs() -> Vec { read_wan_ipv4_addrs().unwrap_or_default() } -/// `None` when ubus is unavailable; empty when the interface is down. +/// `None` when ubus is unavailable; empty when the uplink is down. pub(crate) fn read_wan_ipv4_addrs() -> Option> { let out = StdCommand::new("ubus") - .args(["call", "network.interface.wan", "status"]) + .args(["call", "network.interface", "dump"]) .output() .ok()?; if !out.status.success() { return None; } - let json = serde_json::from_slice::(&out.stdout).ok()?; - Some( - json.get("ipv4-address") - .and_then(|v| v.as_array()) - .map(|arr| { - arr.iter() - .filter_map(|e| e.get("address")?.as_str()?.parse().ok()) - .collect() - }) - .unwrap_or_default(), - ) + let dump = serde_json::from_slice::(&out.stdout).ok()?; + Some(uplink_ipv4_addrs(&dump)) } pub async fn get_wan_ipv6s() -> Result, Error> { @@ -1020,6 +1062,74 @@ pub fn system() -> ParentHandler { mod tests { use super::*; + /// One interface of `network.interface dump`, shaped like netifd's output. + fn iface( + name: &str, + up: bool, + metric: u32, + address: &str, + default_route: bool, + ) -> serde_json::Value { + let route = if default_route { + serde_json::json!([{ "target": "0.0.0.0", "mask": 0, "nexthop": "192.0.2.1" }]) + } else { + serde_json::json!([]) + }; + let addresses = if up { + serde_json::json!([{ "address": address, "mask": 24 }]) + } else { + serde_json::json!([]) + }; + serde_json::json!({ + "interface": name, + "up": up, + "metric": metric, + "ipv4-address": addresses, + "route": route, + }) + } + + fn uplink(interfaces: Vec) -> (Option, Vec) { + let dump = serde_json::json!({ "interface": interfaces }); + ( + uplink_status(&dump) + .and_then(|i| i.get("interface")?.as_str()) + .map(String::from), + uplink_ipv4_addrs(&dump), + ) + } + + #[test] + fn uplink_follows_the_default_route() { + let lan = iface("lan", true, 0, "192.168.1.1", false); + let wan = |up, metric| iface("wan", up, metric, "203.0.113.5", up); + let wwan = |up, metric| iface("wwan", up, metric, "10.0.0.7", up); + let wan_addr: Ipv4Addr = "203.0.113.5".parse().unwrap(); + let wwan_addr: Ipv4Addr = "10.0.0.7".parse().unwrap(); + + assert_eq!( + uplink(vec![lan.clone(), wan(true, 0)]), + (Some("wan".into()), vec![wan_addr]) + ); + assert_eq!( + uplink(vec![lan.clone(), wan(true, 10), wwan(true, 20)]), + (Some("wan".into()), vec![wan_addr]) + ); + assert_eq!( + uplink(vec![lan.clone(), wan(true, 20), wwan(true, 10)]), + (Some("wwan".into()), vec![wwan_addr]) + ); + assert_eq!( + uplink(vec![lan.clone(), wan(false, 10), wwan(true, 20)]), + (Some("wwan".into()), vec![wwan_addr]) + ); + assert_eq!( + uplink(vec![lan.clone(), wan(false, 10), wwan(false, 20)]), + (Some("wan".into()), vec![]) + ); + assert_eq!(uplink(vec![lan]), (None, vec![])); + } + #[test] fn test_cmp_versions_prerelease() { use std::cmp::Ordering; diff --git a/projects/start-wrt/backend/ctrl/src/wan.rs b/projects/start-wrt/backend/ctrl/src/wan.rs index 272f6d5db1..efd10a6d20 100644 --- a/projects/start-wrt/backend/ctrl/src/wan.rs +++ b/projects/start-wrt/backend/ctrl/src/wan.rs @@ -22,6 +22,10 @@ fn serde_name(v: &impl Serialize) -> String { pub const WAN_INTERFACE: &str = "wan"; pub const WAN6_INTERFACE: &str = "wan6"; +/// The Wi-Fi uplink, a member of the `wan` firewall zone. +pub const WWAN_INTERFACE: &str = "wwan"; +/// Interfaces whose upstream DNS servers follow the WAN DNS mode. +const DNS_INTERFACES: [&str; 3] = [WAN_INTERFACE, WAN6_INTERFACE, WWAN_INTERFACE]; /// netifd alias for the `wan` interface's layer-3 device. pub const WAN6_DEVICE: &str = "@wan"; const DDNS_SECTION: &str = "wan"; @@ -918,6 +922,33 @@ pub async fn dns_get(ctx: C) -> Result { } } +/// The DNS options of an interface, written without touching its other options. +#[derive(Debug, TypedSection, Default)] +#[uci(ty = "interface")] +struct InterfaceDns { + #[uci(default)] + peerdns: Option, + dns: Vec, +} + +/// Off keeps the upstream network's DNS servers out of dnsmasq's resolv file. +fn set_peer_dns(cfgs: &mut uciedit::Configs, peer_dns: bool) -> Result<(), Error> { + for section in &mut cfgs["network"].sections { + if !section + .name() + .is_some_and(|n| DNS_INTERFACES.contains(&&*n)) + { + continue; + } + if let Some(mut iface) = section.get_typed::()? { + iface.peerdns = Some(if peer_dns { "1" } else { "0" }.to_string()); + iface.dns = vec![]; + section.set(&iface)?; + } + } + Ok(()) +} + #[instrument(skip_all)] pub async fn dns_set( ctx: C, @@ -948,33 +979,9 @@ pub async fn dns_set( Some("system_dns"), )?; - // Set peerdns=0 on WAN/WAN6 to prevent ISP DNS from appearing in resolvfile - for section in &mut cfgs["network"].sections { - let name = section.name(); - let n = name.as_deref(); - if n == Some(WAN_INTERFACE) || n == Some(WAN6_INTERFACE) { - if let Some(mut iface) = section.get_typed::()? { - iface.peerdns = Some("0".to_string()); - iface.dns = vec![]; - section.set(&iface)?; - } - } - } - } - DnsMode::Isp => { - // Restore peerdns=1 on WAN/WAN6 - for section in &mut cfgs["network"].sections { - let name = section.name(); - let n = name.as_deref(); - if n == Some(WAN_INTERFACE) || n == Some(WAN6_INTERFACE) { - if let Some(mut iface) = section.get_typed::()? { - iface.peerdns = Some("1".to_string()); - iface.dns = vec![]; - section.set(&iface)?; - } - } - } + set_peer_dns(&mut cfgs, false)?; } + DnsMode::Isp => set_peer_dns(&mut cfgs, true)?, } // Rewrite DNS forwarding (dnsmasq + firewall DNAT) for all profiles @@ -1674,6 +1681,54 @@ config zone ); } + #[tokio::test] + async fn dns_mode_follows_onto_the_wifi_uplink() { + let dir = tempfile::tempdir().unwrap(); + setup_network(dir.path()); + setup_startwrt(dir.path()); + let network = std::fs::read_to_string(dir.path().join("network")).unwrap(); + std::fs::write( + dir.path().join("network"), + format!( + "{network}\nconfig interface 'wwan'\n\toption proto 'dhcp'\n\toption metric '20'\n" + ), + ) + .unwrap(); + let ctx = TestContext(dir.path().to_path_buf()); + let wwan = || { + let text = std::fs::read_to_string(dir.path().join("network")).unwrap(); + text[text.find("'wwan'").unwrap()..].to_string() + }; + + dns_set( + ctx.clone(), + DeserializeStdin(WanDnsSetRequest { + mode: DnsMode::Custom, + servers: Some(vec![DnsServer { + address: "9.9.9.9".into(), + ssl: false, + }]), + }), + ) + .await + .unwrap(); + assert!(wwan().contains("option peerdns '0'")); + assert!(wwan().contains("option metric '20'")); + assert!(!wwan().contains("device")); + + dns_set( + ctx, + DeserializeStdin(WanDnsSetRequest { + mode: DnsMode::Isp, + servers: None, + }), + ) + .await + .unwrap(); + assert!(wwan().contains("option peerdns '1'")); + assert!(!wwan().contains("device")); + } + // ── DDNS ── #[tokio::test] diff --git a/projects/start-wrt/backend/ctrl/src/wifi.rs b/projects/start-wrt/backend/ctrl/src/wifi.rs index 95a0524207..33250bddc8 100644 --- a/projects/start-wrt/backend/ctrl/src/wifi.rs +++ b/projects/start-wrt/backend/ctrl/src/wifi.rs @@ -20,8 +20,8 @@ pub const DEFAULT_LAN_BRIDGE: &str = "br-lan"; /// the 64-hex-char raw-PMK form isn't exposed through this API. Reject out-of- /// range lengths at the API boundary so the user gets a clean error instead of /// hostapd silently refusing to start the AP. -const MIN_PSK_LEN: usize = 8; -const MAX_PSK_LEN: usize = 63; +pub(crate) const MIN_PSK_LEN: usize = 8; +pub(crate) const MAX_PSK_LEN: usize = 63; const REGULATORY_DB: &str = "/lib/firmware/regulatory.db"; @@ -836,6 +836,27 @@ fn auto_enable_radios_on_first_admin_password( Ok(true) } +/// Turning off a radio a client-mode interface uses would drop that uplink. +fn check_uplink_radios(cfgs: &Configs, radios: &BTreeMap) -> Result<(), Error> { + let uplinks = crate::wwan::uplink_radios(cfgs)?; + for (_, iface, _, radio) in find_relevant_with_radios(cfgs, radios)? { + if !radio.enabled && uplinks.contains(&iface.device) { + crate::activity::log( + "wifi", + "updated", + false, + "Failed to update WiFi: radio carries the Wi-Fi uplink", + Some("WifiRadioCarriesUplink"), + ); + return Err(Error::new( + eyre!("radio {} carries a Wi-Fi uplink", iface.device), + ErrorKind::WifiRadioCarriesUplink, + )); + } + } + Ok(()) +} + /// Determines whether a full wifi restart or PSK-only reload is needed. fn set_config( _ctx: &impl CtrlContext, @@ -1099,6 +1120,11 @@ pub async fn set( } if preview { + { + let arena = Arena::new(); + let cfgs = parse_all(ctx.uci_root(), &arena, &["wireless"]).await?; + check_uplink_radios(&cfgs, &wifi.radios)?; + } let leaving_profile = if ctx.effectful() { wifi_devices_leaving_profile(&ctx, &wifi).await? } else { @@ -1228,6 +1254,7 @@ pub async fn set( ); return Err(err); } + check_uplink_radios(&cfgs, &wifi.radios)?; let restart = match set_config(&ctx, &mut cfgs, &wifi, &lookup) { Err(Error { kind: ErrorKind::CorruptedWifi, @@ -4117,4 +4144,94 @@ Band 2: assert!(written.contains("option htmode 'HE80'"), "{written}"); assert!(written.contains("option country 'US'"), "{written}"); } + + #[tokio::test] + async fn turning_off_a_radio_that_carries_an_uplink_is_refused() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + dir.path().join("wireless"), + "\ +config wifi-device 'radio0' +\toption type 'mac80211' +\toption band '2g' +\toption channel 'auto' + +config wifi-iface 'default_radio0' +\toption device 'radio0' +\toption mode 'ap' +\toption ssid 'Start9' +\toption encryption 'psk2' +\toption key 'adminpassword' + +config wifi-iface 'wifinet2' +\toption device 'radio0' +\toption mode 'sta' +\toption network 'wwan' +\toption ssid 'Upstream' +", + ) + .unwrap(); + let arena = Arena::new(); + let cfgs = parse_all(dir.path().to_path_buf(), &arena, &["wireless"]) + .await + .unwrap(); + let radio = |enabled| { + BTreeMap::from([( + "default_radio0".to_string(), + WifiRadio { + band: "2g".into(), + channel: "auto".into(), + width: None, + enabled, + broadcast: enabled, + }, + )]) + }; + check_uplink_radios(&cfgs, &radio(true)).unwrap(); + let err = check_uplink_radios(&cfgs, &radio(false)).unwrap_err(); + assert_eq!(err.kind, ErrorKind::WifiRadioCarriesUplink); + } + + #[tokio::test] + async fn preview_refuses_turning_off_an_uplink_radio() { + let dir = tempfile::tempdir().unwrap(); + let ctx = TestContext(dir.path().to_path_buf()); + setup_test_configs(dir.path()); + write_wireless_config_unkeyed(dir.path()); + let mut wireless = std::fs::read_to_string(dir.path().join("wireless")).unwrap(); + wireless.push_str( + "\nconfig wifi-iface 'wwan'\n\toption device 'radio0'\n\toption mode 'sta'\n\toption network 'wwan'\n\toption ssid 'Upstream'\n", + ); + std::fs::write(dir.path().join("wireless"), &wireless).unwrap(); + + let request = |radios| { + let mut passwords = BTreeSet::>::new(); + passwords.insert(Password { + label: "Admin".into(), + profile: None, + password: "adminpass1".into(), + }); + DeserializeStdin(super::WifiSetRequest { + wifi: Wifi { + ssid: "TestNet".into(), + broadcast_separately: false, + country: None, + radios, + passwords, + }, + preview: true, + }) + }; + super::set(ctx.clone(), request(make_dual_radios())) + .await + .unwrap(); + let err = super::set(ctx, request(make_dual_radios_disabled())) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::WifiRadioCarriesUplink); + assert_eq!( + std::fs::read_to_string(dir.path().join("wireless")).unwrap(), + wireless + ); + } } diff --git a/projects/start-wrt/backend/ctrl/src/wwan.rs b/projects/start-wrt/backend/ctrl/src/wwan.rs new file mode 100644 index 0000000000..92f101cdd2 --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/wwan.rs @@ -0,0 +1,1243 @@ +//! Wireless WAN: the router joins another Wi-Fi network as an uplink. +//! +//! StartWRT owns the `wwan` sections of `wireless` and `network`. The uplink +//! interface joins the `wan` firewall zone, so profiles that route through the +//! WAN, published ports and remote access treat it as the WAN. netifd picks the +//! uplink with the lower route metric while both have a default route. + +use std::collections::{BTreeMap, BTreeSet}; + +use rpc_toolkit::{from_fn_async_local, ParentHandler}; +use serde::{Deserialize, Serialize}; +use uciedit::openwrt::{FirewallZone, InterfaceProto, WifiDevice, WifiMode}; +use uciedit::{dump_all, parse_all, Arena, Configs, TypedSection}; + +use crate::invoke::Invoke; +use crate::prelude::*; +use crate::profiles::{self, DEFAULT_WAN_ZONE}; +use crate::utils::{DeserializeStdin, HandlerExtSerde}; +use crate::wan::{WAN_INTERFACE, WWAN_INTERFACE}; +use crate::CtrlContext; + +/// Route metric of the uplink that carries traffic while both are up. +const PREFERRED_METRIC: u32 = 10; +/// Route metric of the uplink held in reserve. +const BACKUP_METRIC: u32 = 20; + +const MAX_SSID_LEN: usize = 32; + +/// A client-mode Wi-Fi interface, read without the access-point options. +#[derive(Debug, Clone, TypedSection)] +#[uci(ty = "wifi-iface")] +struct UplinkStation { + device: String, + #[uci(default)] + mode: WifiMode, + #[uci(default)] + network: Option, + #[uci(default)] + ssid: String, + #[uci(default_value = "none".to_string())] + encryption: String, + #[uci(default)] + key: Option, + #[uci(default_value = false)] + disabled: bool, +} + +/// The uplink's network interface. A wireless interface names no `device`. +#[derive(Debug, Default, TypedSection)] +#[uci(ty = "interface")] +struct UplinkInterface { + #[uci(default)] + proto: InterfaceProto, + #[uci(default)] + metric: Option, + #[uci(default)] + peerdns: Option, + #[uci(default)] + dns: Vec, +} + +/// The `metric` option of an interface, written without touching its other options. +#[derive(Debug, Default, TypedSection)] +#[uci(ty = "interface")] +struct InterfaceMetric { + #[uci(default)] + metric: Option, +} + +// ── Types ─────────────────────────────────────────────────── + +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, visit_rs::VisitVariants)] +#[serde(rename_all = "camelCase")] +pub enum WwanSecurity { + Open, + Wpa2, + Wpa2Wpa3, + Wpa3, +} +rpc_toolkit::reflect_ts!(WwanSecurity); + +impl WwanSecurity { + fn encryption(self) -> &'static str { + match self { + WwanSecurity::Open => "none", + WwanSecurity::Wpa2 => "psk2", + WwanSecurity::Wpa2Wpa3 => "sae-mixed", + WwanSecurity::Wpa3 => "sae", + } + } + + /// `None` for an encryption StartWRT does not offer, such as WPA Enterprise. + fn from_encryption(encryption: &str) -> Option { + match encryption.split('+').next()? { + "none" => Some(WwanSecurity::Open), + "psk2" | "psk-mixed" => Some(WwanSecurity::Wpa2), + "sae-mixed" => Some(WwanSecurity::Wpa2Wpa3), + "sae" => Some(WwanSecurity::Wpa3), + _ => None, + } + } +} + +/// Which uplink carries traffic while both the WAN port and the Wi-Fi uplink are up. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, visit_rs::VisitVariants)] +#[serde(rename_all = "camelCase")] +pub enum WwanPriority { + /// Used while the WAN port has no connection. + Backup, + /// Used while connected; the WAN port takes over when it drops. + Preferred, +} +rpc_toolkit::reflect_ts!(WwanPriority); + +#[derive(Debug, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanRadio { + /// The `wifi-device` section, e.g. `radio0`. + pub radio: String, + pub band: String, + pub enabled: bool, +} +rpc_toolkit::reflect_ts!(WwanRadio); + +#[derive(Debug, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanUplink { + pub radio: String, + pub band: String, + pub ssid: String, + pub security: WwanSecurity, + pub priority: WwanPriority, +} +rpc_toolkit::reflect_ts!(WwanUplink); + +/// What the router observes of the uplink. Absent off the router. +#[derive(Debug, Default, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanState { + pub associated: bool, + /// The uplink's IPv4 address, once DHCP has assigned one. + pub address: Option, + /// Signal strength in dBm. + pub signal: Option, + pub channel: Option, + /// Whether the router's Internet traffic leaves through the Wi-Fi uplink. + pub active: bool, +} +rpc_toolkit::reflect_ts!(WwanState); + +#[derive(Debug, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanResponse { + pub radios: Vec, + pub uplink: Option, + pub state: Option, + /// Client-mode Wi-Fi interfaces StartWRT did not create, by section name. + pub unmanaged: Vec, +} +rpc_toolkit::reflect_ts!(WwanResponse); + +#[derive(Debug, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanScanRequest { + pub radio: String, +} +rpc_toolkit::reflect_ts!(WwanScanRequest); + +#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanNetwork { + /// Empty for a network that hides its name. + pub ssid: String, + pub bssid: String, + pub channel: Option, + /// Signal strength in dBm. + pub signal: Option, + /// `None` for a network StartWRT cannot join, such as WPA Enterprise. + pub security: Option, +} +rpc_toolkit::reflect_ts!(WwanNetwork); + +#[derive(Debug, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanConnectRequest { + pub radio: String, + pub ssid: String, + pub security: WwanSecurity, + /// Ignored for an open network. + pub password: Option, + pub priority: WwanPriority, +} +rpc_toolkit::reflect_ts!(WwanConnectRequest); + +#[derive(Debug, Serialize, Deserialize, visit_rs::VisitFields)] +#[serde(rename_all = "camelCase")] +pub struct WwanPrioritySetRequest { + pub priority: WwanPriority, +} +rpc_toolkit::reflect_ts!(WwanPrioritySetRequest); + +// ── Route registration ────────────────────────────────────── + +pub fn wwan() -> ParentHandler { + ParentHandler::new() + .subcommand( + "get", + from_fn_async_local(get::).with_display_serializable(), + ) + .subcommand( + "scan", + from_fn_async_local(scan::).with_display_serializable(), + ) + .subcommand( + "connect", + from_fn_async_local(connect::).with_display_serializable(), + ) + .subcommand( + "priority-set", + from_fn_async_local(priority_set::).with_display_serializable(), + ) + .subcommand( + "disconnect", + from_fn_async_local(disconnect::).with_display_serializable(), + ) +} + +// ── Config reads ──────────────────────────────────────────── + +fn radios(cfgs: &Configs) -> Result, Error> { + let mut radios = BTreeMap::new(); + cfgs["wireless"].try_each(|name, device: WifiDevice| { + if let Some(name) = name { + radios.insert(name.to_string(), device); + } + Ok::<_, Error>(()) + })?; + Ok(radios) +} + +fn stations(cfgs: &Configs) -> Result, UplinkStation)>, Error> { + let mut stations = Vec::new(); + cfgs["wireless"].try_each(|name, station: UplinkStation| { + if station.mode == WifiMode::STA { + stations.push((name.map(|n| n.to_string()), station)); + } + Ok::<_, Error>(()) + })?; + Ok(stations) +} + +/// Radios an enabled client-mode interface uses, whoever configured it. +pub(crate) fn uplink_radios(cfgs: &Configs) -> Result, Error> { + Ok(stations(cfgs)? + .into_iter() + .filter(|(_, s)| !s.disabled) + .map(|(_, s)| s.device) + .collect()) +} + +fn interface_metric(cfgs: &Configs, name: &str) -> Result, Error> { + for section in &cfgs["network"].sections { + if section.name().as_deref() == Some(name) { + if let Some(iface) = section.get_typed::()? { + return Ok(iface.metric); + } + } + } + Ok(None) +} + +fn priority_of(cfgs: &Configs) -> Result { + let wan = interface_metric(cfgs, WAN_INTERFACE)?.unwrap_or(0); + let wwan = interface_metric(cfgs, WWAN_INTERFACE)?.unwrap_or(0); + Ok(if wwan < wan { + WwanPriority::Preferred + } else { + WwanPriority::Backup + }) +} + +fn get_config(cfgs: &Configs) -> Result { + let radios_by_name = radios(cfgs)?; + let mut uplink = None; + let mut unmanaged = Vec::new(); + for (name, station) in stations(cfgs)? { + if name.as_deref() != Some(WWAN_INTERFACE) { + unmanaged.push(name.unwrap_or_default()); + continue; + } + let security = WwanSecurity::from_encryption(&station.encryption).ok_or_else(|| { + Error::new( + eyre!("unsupported uplink encryption {}", station.encryption), + ErrorKind::InvalidValue, + ) + })?; + uplink = Some(WwanUplink { + band: radios_by_name + .get(&station.device) + .map(|d| d.band.clone()) + .unwrap_or_default(), + radio: station.device, + ssid: station.ssid, + security, + priority: priority_of(cfgs)?, + }); + } + Ok(WwanResponse { + radios: radios_by_name + .into_iter() + .map(|(radio, device)| WwanRadio { + radio, + band: device.band, + enabled: !device.disabled, + }) + .collect(), + uplink, + state: None, + unmanaged, + }) +} + +// ── Router state ──────────────────────────────────────────── + +#[derive(Debug, Default, Deserialize)] +struct RadioStatus { + #[serde(default)] + interfaces: Vec, +} + +#[derive(Debug, Default, Deserialize)] +struct RadioInterfaceStatus { + #[serde(default)] + section: Option, + #[serde(default)] + ifname: Option, +} + +/// `None` when the object is missing or ubus is unavailable. +async fn ubus_call( + object: &str, + method: &str, + args: Option, +) -> Option { + let mut cmd = tokio::process::Command::new("ubus"); + cmd.args(["call", object, method]); + if let Some(args) = args { + cmd.arg(args.to_string()); + } + let out = cmd.invoke(ErrorKind::Network.into()).await.ok()?; + serde_json::from_slice(&out).ok() +} + +async fn wireless_status() -> Option> { + serde_json::from_value(ubus_call("network.wireless", "status", None).await?).ok() +} + +/// The kernel interface netifd created for a `wifi-iface` section. +fn ifname_of<'a>(status: &'a BTreeMap, section: &str) -> Option<&'a str> { + status + .values() + .flat_map(|r| &r.interfaces) + .find(|i| i.section.as_deref() == Some(section))? + .ifname + .as_deref() +} + +async fn read_state() -> WwanState { + let mut state = WwanState::default(); + if let Some(status) = ubus_call("network.interface.wwan", "status", None).await { + state.address = status + .pointer("/ipv4-address/0/address") + .and_then(|v| v.as_str()) + .map(String::from); + } + let radios = wireless_status().await.unwrap_or_default(); + if let Some(ifname) = ifname_of(&radios, WWAN_INTERFACE) { + if let Some(info) = ubus_call( + "iwinfo", + "info", + Some(serde_json::json!({ "device": ifname })), + ) + .await + { + state.associated = info + .get("bssid") + .and_then(|v| v.as_str()) + .is_some_and(|b| !b.is_empty() && b != "00:00:00:00:00:00"); + state.signal = info + .get("signal") + .and_then(|v| v.as_i64()) + .map(|s| s as i32); + state.channel = info + .get("channel") + .and_then(|v| v.as_u64()) + .map(|c| c as u32); + } + } + state.active = crate::system::active_uplink().await.as_deref() == Some(WWAN_INTERFACE); + state +} + +// ── Scan results ──────────────────────────────────────────── + +#[derive(Debug, Default, Deserialize)] +struct ScanResult { + #[serde(default)] + ssid: Option, + #[serde(default)] + bssid: String, + #[serde(default)] + channel: Option, + #[serde(default)] + signal: Option, + #[serde(default)] + encryption: ScanEncryption, +} + +#[derive(Debug, Default, Deserialize)] +struct ScanEncryption { + #[serde(default)] + enabled: bool, + #[serde(default)] + wep: Option, + #[serde(default)] + wpa: Vec, + #[serde(default)] + authentication: Vec, +} + +impl ScanEncryption { + fn security(&self) -> Option { + if !self.enabled { + return Some(WwanSecurity::Open); + } + if self.wep.is_some() || self.authentication.iter().any(|a| a != "psk" && a != "sae") { + return None; + } + let psk = self.authentication.iter().any(|a| a == "psk"); + let sae = self.authentication.iter().any(|a| a == "sae"); + match (psk, sae) { + (true, true) => Some(WwanSecurity::Wpa2Wpa3), + (false, true) => Some(WwanSecurity::Wpa3), + (true, false) if self.wpa.iter().any(|v| *v >= 2) => Some(WwanSecurity::Wpa2), + _ => None, + } + } +} + +/// One entry per network name, strongest signal first. Hidden networks keep +/// one entry per access point. +fn scan_networks(results: Vec) -> Vec { + let mut networks: Vec = Vec::new(); + for result in results { + let ssid = result.ssid.unwrap_or_default(); + let network = WwanNetwork { + security: result.encryption.security(), + ssid, + bssid: result.bssid, + channel: result.channel, + signal: result.signal, + }; + match networks + .iter_mut() + .find(|n| !n.ssid.is_empty() && n.ssid == network.ssid) + { + Some(existing) if existing.signal < network.signal => *existing = network, + Some(_) => {} + None => networks.push(network), + } + } + networks.sort_by(|a, b| b.signal.cmp(&a.signal)); + networks +} + +// ── Config writes ─────────────────────────────────────────── + +fn validate(req: &WwanConnectRequest, radios: &BTreeMap) -> Result<(), Error> { + if radios.get(&req.radio).map_or(true, |d| d.disabled) { + return Err(Error::new( + eyre!("radio {} is off or missing", req.radio), + ErrorKind::WifiRadioUnavailable, + )); + } + if req.ssid.is_empty() || req.ssid.len() > MAX_SSID_LEN { + return Err(Error::new( + eyre!("network name must be 1 to {MAX_SSID_LEN} bytes"), + ErrorKind::InvalidValue, + )); + } + if req.security != WwanSecurity::Open { + let len = req.password.as_deref().map_or(0, str::len); + if !(crate::wifi::MIN_PSK_LEN..=crate::wifi::MAX_PSK_LEN).contains(&len) { + return Err(Error::new( + eyre!( + "password must be {} to {} characters", + crate::wifi::MIN_PSK_LEN, + crate::wifi::MAX_PSK_LEN + ), + ErrorKind::InvalidValue, + )); + } + } + Ok(()) +} + +fn set_metrics(cfgs: &mut Configs, priority: WwanPriority) -> Result<(), Error> { + let (wan, wwan) = match priority { + WwanPriority::Backup => (PREFERRED_METRIC, BACKUP_METRIC), + WwanPriority::Preferred => (BACKUP_METRIC, PREFERRED_METRIC), + }; + for section in &mut cfgs["network"].sections { + let metric = match section.name().as_deref() { + Some(WAN_INTERFACE) => wan, + Some(WWAN_INTERFACE) => wwan, + _ => continue, + }; + if let Some(mut iface) = section.get_typed::()? { + iface.metric = Some(metric); + section.set(&iface)?; + } + } + Ok(()) +} + +fn set_zone_membership(cfgs: &mut Configs, member: bool) -> Result<(), Error> { + for section in &mut cfgs["firewall"].sections { + let Ok(mut zone) = section.get::() else { + continue; + }; + if zone.name != DEFAULT_WAN_ZONE { + continue; + } + let present = zone.network.iter().any(|n| n == WWAN_INTERFACE); + if member && !present { + zone.network.push(WWAN_INTERFACE.to_string()); + } else if !member && present { + zone.network.retain(|n| n != WWAN_INTERFACE); + } else { + return Ok(()); + } + section.set(&zone)?; + return Ok(()); + } + Err(Error::new( + eyre!("firewall zone {DEFAULT_WAN_ZONE} not found"), + ErrorKind::MissingFirewallZone, + )) +} + +fn remove_sections(cfgs: &mut Configs) { + for config in ["wireless", "network"] { + cfgs[config] + .sections + .retain(|s| s.name().as_deref() != Some(WWAN_INTERFACE)); + } +} + +fn apply_connect(cfgs: &mut Configs, req: &WwanConnectRequest) -> Result<(), Error> { + let radios = radios(cfgs)?; + validate(req, &radios)?; + let unmanaged: Vec = stations(cfgs)? + .into_iter() + .filter_map(|(name, _)| { + (name.as_deref() != Some(WWAN_INTERFACE)).then(|| name.unwrap_or_default()) + }) + .collect(); + if !unmanaged.is_empty() { + return Err(Error::new( + eyre!( + "a Wi-Fi uplink set up outside StartWRT exists: {}", + unmanaged.join(", ") + ), + ErrorKind::WifiUplinkConfiguredElsewhere, + )); + } + let custom_dns = !crate::dns::get_system_dns_servers(cfgs).is_empty(); + + remove_sections(cfgs); + cfgs["wireless"].append( + &UplinkStation { + device: req.radio.clone(), + mode: WifiMode::STA, + network: Some(WWAN_INTERFACE.to_string()), + ssid: req.ssid.clone(), + encryption: req.security.encryption().to_string(), + key: (req.security != WwanSecurity::Open) + .then(|| req.password.clone()) + .flatten(), + disabled: false, + }, + Some(WWAN_INTERFACE), + )?; + cfgs["network"].append( + &UplinkInterface { + proto: InterfaceProto::DHCP, + metric: None, + peerdns: custom_dns.then(|| "0".to_string()), + dns: Vec::new(), + }, + Some(WWAN_INTERFACE), + )?; + set_metrics(cfgs, req.priority)?; + set_zone_membership(cfgs, true)?; + Ok(()) +} + +fn apply_disconnect(cfgs: &mut Configs) -> Result<(), Error> { + remove_sections(cfgs); + set_zone_membership(cfgs, false)?; + for section in &mut cfgs["network"].sections { + if section.name().as_deref() == Some(WAN_INTERFACE) { + if let Some(mut iface) = section.get_typed::()? { + iface.metric = None; + section.set(&iface)?; + } + } + } + Ok(()) +} + +fn require_uplink(cfgs: &Configs) -> Result<(), Error> { + if stations(cfgs)? + .iter() + .any(|(name, _)| name.as_deref() == Some(WWAN_INTERFACE)) + { + Ok(()) + } else { + Err(Error::new(eyre!("no Wi-Fi uplink"), ErrorKind::NotFound)) + } +} + +/// Re-reads, re-applies and writes on a config conflict, then logs the outcome. +async fn write( + ctx: &C, + action: &str, + summary: &str, + apply: impl Fn(&mut Configs) -> Result<(), Error>, +) -> Result<(), Error> { + let mut retries = 4; + loop { + let arena = Arena::new(); + let mut cfgs = parse_all( + ctx.uci_root(), + &arena, + &["wireless", "network", "firewall", "startwrt"], + ) + .await?; + if let Err(err) = apply(&mut cfgs) { + crate::activity::log("wwan", action, false, summary, Some(&err.to_string())); + return Err(err); + } + let dump_result = dump_all(ctx.uci_root(), cfgs).await; + drop(arena); + match dump_result { + Err(uciedit::Error::Conflict { .. }) if retries > 0 => { + retries -= 1; + } + Err(err) => { + crate::activity::log("wwan", action, false, summary, Some(&err.to_string())); + return Err(err.into()); + } + Ok(()) => { + crate::activity::log("wwan", action, true, summary, None); + if ctx.effectful() { + profiles::reload_system().await?; + } + return Ok(()); + } + } + } +} + +// ── Handlers ──────────────────────────────────────────────── + +#[instrument(skip_all)] +pub async fn get(ctx: C) -> Result { + let mut res = { + let arena = Arena::new(); + let cfgs = parse_all(ctx.uci_root(), &arena, &["wireless", "network"]).await?; + get_config(&cfgs)? + }; + if ctx.effectful() && res.uplink.is_some() { + res.state = Some(read_state().await); + } + Ok(res) +} + +#[instrument(skip_all)] +pub async fn scan( + ctx: C, + DeserializeStdin(req): DeserializeStdin, +) -> Result, Error> { + let enabled = { + let arena = Arena::new(); + let cfgs = parse_all(ctx.uci_root(), &arena, &["wireless"]).await?; + radios(&cfgs)?.get(&req.radio).map(|d| !d.disabled) + }; + if enabled != Some(true) { + return Err(Error::new( + eyre!("radio {} is off or missing", req.radio), + ErrorKind::WifiRadioUnavailable, + )); + } + if !ctx.effectful() { + return Ok(Vec::new()); + } + // iwinfo resolves a radio name to one of its interfaces, or a temporary one. + let results = tokio::process::Command::new("ubus") + .args([ + "-t", + "30", + "call", + "iwinfo", + "scan", + &serde_json::json!({ "device": req.radio }).to_string(), + ]) + .invoke(ErrorKind::Network.into()) + .await?; + #[derive(Deserialize)] + struct Scan { + #[serde(default)] + results: Vec, + } + let scan: Scan = + serde_json::from_slice(&results).map_err(|e| Error::new(e, ErrorKind::Deserialization))?; + Ok(scan_networks(scan.results)) +} + +#[instrument(skip_all)] +pub async fn connect( + ctx: C, + DeserializeStdin(req): DeserializeStdin, +) -> Result<(), Error> { + write( + &ctx, + "connected", + &format!("Joined Wi-Fi uplink {}", req.ssid), + |cfgs| apply_connect(cfgs, &req), + ) + .await +} + +#[instrument(skip_all)] +pub async fn priority_set( + ctx: C, + DeserializeStdin(req): DeserializeStdin, +) -> Result<(), Error> { + let summary = match req.priority { + WwanPriority::Backup => "Set Wi-Fi uplink as backup", + WwanPriority::Preferred => "Set Wi-Fi uplink as preferred", + }; + write(&ctx, "priority-updated", summary, |cfgs| { + require_uplink(cfgs)?; + set_metrics(cfgs, req.priority) + }) + .await +} + +#[instrument(skip_all)] +pub async fn disconnect(ctx: C) -> Result<(), Error> { + write(&ctx, "disconnected", "Removed Wi-Fi uplink", |cfgs| { + require_uplink(cfgs)?; + apply_disconnect(cfgs) + }) + .await +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + use std::sync::Arc; + + use rpc_toolkit::Context; + use tokio::runtime::Runtime; + + use super::*; + + #[derive(Clone)] + struct TestContext(PathBuf); + + impl Context for TestContext { + fn runtime(&self) -> Option> { + None + } + } + + impl CtrlContext for TestContext { + fn uci_root(&self) -> PathBuf { + self.0.clone() + } + fn effectful(&self) -> bool { + false + } + } + + const WIRELESS: &str = "\ +config wifi-device 'radio0' +\toption type 'mac80211' +\toption band '2g' +\toption channel 'auto' + +config wifi-device 'radio1' +\toption type 'mac80211' +\toption band '5g' +\toption channel '36' +\toption disabled '1' + +config wifi-iface 'default_radio0' +\toption device 'radio0' +\toption mode 'ap' +\toption network 'lan' +\toption ssid 'Start9' +\toption encryption 'psk2' +\toption key 'adminpassword' +"; + + const LUCI_UPLINK: &str = " +config wifi-iface 'wifinet2' +\toption device 'radio0' +\toption mode 'sta' +\toption network 'wwan' +\toption ssid 'Upstream' +\toption encryption 'psk2' +\toption key 'upstreampass' +"; + + fn setup(dir: &Path, wireless: &str, startwrt: &str) -> TestContext { + std::fs::write(dir.join("wireless"), wireless).unwrap(); + std::fs::write( + dir.join("network"), + "\ +config interface 'wan' +\toption device 'eth1' +\toption proto 'dhcp' + +config interface 'wan6' +\toption device '@wan' +\toption proto 'dhcpv6' +", + ) + .unwrap(); + std::fs::write( + dir.join("firewall"), + "\ +config zone 'wan_zone' +\toption name 'wan' +\toption input 'REJECT' +\toption output 'ACCEPT' +\toption forward 'REJECT' +\tlist network 'wan' +\tlist network 'wan6' +", + ) + .unwrap(); + std::fs::write(dir.join("startwrt"), startwrt).unwrap(); + TestContext(dir.to_path_buf()) + } + + fn connect_req(security: WwanSecurity, password: Option<&str>) -> WwanConnectRequest { + WwanConnectRequest { + radio: "radio0".into(), + ssid: "Upstream".into(), + security, + password: password.map(String::from), + priority: WwanPriority::Backup, + } + } + + fn read(dir: &Path, config: &str) -> String { + std::fs::read_to_string(dir.join(config)).unwrap() + } + + /// Every section with this name, as its text. A header names it quoted or bare. + fn sections(dir: &Path, config: &str, name: &str) -> Vec { + let mut found = Vec::new(); + let mut current: Option = None; + for line in read(dir, config).lines() { + if line.starts_with("config ") { + found.extend(current.take()); + let named = line.split_whitespace().nth(2).map(|n| n.trim_matches('\'')); + if named == Some(name) { + current = Some(String::new()); + } + } + if let Some(body) = &mut current { + body.push_str(line); + body.push('\n'); + } + } + found.extend(current); + found + } + + fn section(dir: &Path, config: &str, name: &str) -> Option { + sections(dir, config, name).into_iter().next() + } + + #[tokio::test] + async fn connect_writes_uplink_as_backup() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + + let station = section(dir.path(), "wireless", WWAN_INTERFACE).unwrap(); + assert!(station.contains("option mode 'sta'")); + assert!(station.contains("option network 'wwan'")); + assert!(station.contains("option encryption 'psk2'")); + assert!(station.contains("option key 'upstreampass'")); + let iface = section(dir.path(), "network", WWAN_INTERFACE).unwrap(); + assert!(iface.contains("option proto 'dhcp'")); + assert!(iface.contains("option metric '20'")); + assert!(!iface.contains("device")); + assert!(!iface.contains("peerdns")); + assert!(section(dir.path(), "network", WAN_INTERFACE) + .unwrap() + .contains("option metric '10'")); + assert!(read(dir.path(), "firewall").contains("list network 'wwan'")); + // The access point on the same radio is untouched. + assert!(section(dir.path(), "wireless", "default_radio0") + .unwrap() + .contains("option key 'adminpassword'")); + + let res = get(ctx).await.unwrap(); + let uplink = res.uplink.unwrap(); + assert_eq!(uplink.radio, "radio0"); + assert_eq!(uplink.band, "2g"); + assert_eq!(uplink.ssid, "Upstream"); + assert_eq!(uplink.security, WwanSecurity::Wpa2); + assert_eq!(uplink.priority, WwanPriority::Backup); + assert!(res.unmanaged.is_empty()); + assert!(res.state.is_none()); + } + + #[tokio::test] + async fn connect_again_replaces_the_uplink() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + let mut req = connect_req(WwanSecurity::Open, Some("ignored-password")); + req.ssid = "Cafe".into(); + connect(ctx.clone(), DeserializeStdin(req)).await.unwrap(); + + assert_eq!(sections(dir.path(), "wireless", WWAN_INTERFACE).len(), 1); + let station = section(dir.path(), "wireless", WWAN_INTERFACE).unwrap(); + assert!(station.contains("option ssid 'Cafe'")); + assert!(station.contains("option encryption 'none'")); + assert!(!station.contains("key")); + assert_eq!(sections(dir.path(), "network", WWAN_INTERFACE).len(), 1); + assert_eq!( + read(dir.path(), "firewall") + .matches("list network 'wwan'") + .count(), + 1 + ); + } + + #[tokio::test] + async fn connect_keeps_custom_dns_off_the_uplink() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup( + dir.path(), + WIRELESS, + "config system_dns 'system_dns'\n\tlist servers '{\"address\":\"9.9.9.9\",\"ssl\":false}'\n", + ); + connect( + ctx, + DeserializeStdin(connect_req(WwanSecurity::Wpa3, Some("upstreampass"))), + ) + .await + .unwrap(); + let iface = section(dir.path(), "network", WWAN_INTERFACE).unwrap(); + assert!(iface.contains("option peerdns '0'")); + assert!(section(dir.path(), "wireless", WWAN_INTERFACE) + .unwrap() + .contains("option encryption 'sae'")); + } + + #[tokio::test] + async fn connect_rejects_bad_requests() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + let before = read(dir.path(), "wireless"); + + let err = connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("short"))), + ) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidValue); + + let err = connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, None)), + ) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidValue); + + let mut req = connect_req(WwanSecurity::Open, None); + req.ssid = "x".repeat(MAX_SSID_LEN + 1); + let err = connect(ctx.clone(), DeserializeStdin(req)) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidValue); + + let mut req = connect_req(WwanSecurity::Open, None); + req.radio = "radio1".into(); + let err = connect(ctx.clone(), DeserializeStdin(req)) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::WifiRadioUnavailable); + + let mut req = connect_req(WwanSecurity::Open, None); + req.radio = "radio9".into(); + let err = connect(ctx, DeserializeStdin(req)).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::WifiRadioUnavailable); + + assert_eq!(read(dir.path(), "wireless"), before); + } + + #[tokio::test] + async fn uplink_from_luci_is_reported_and_left_alone() { + let dir = tempfile::tempdir().unwrap(); + let wireless = format!("{WIRELESS}{LUCI_UPLINK}"); + let ctx = setup(dir.path(), &wireless, ""); + + let res = get(ctx.clone()).await.unwrap(); + assert!(res.uplink.is_none()); + assert_eq!(res.unmanaged, vec!["wifinet2".to_string()]); + + let err = connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::WifiUplinkConfiguredElsewhere); + assert_eq!(read(dir.path(), "wireless"), wireless); + + let err = disconnect(ctx).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::NotFound); + assert_eq!(read(dir.path(), "wireless"), wireless); + } + + #[tokio::test] + async fn priority_set_swaps_metrics() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + + let err = priority_set( + ctx.clone(), + DeserializeStdin(WwanPrioritySetRequest { + priority: WwanPriority::Preferred, + }), + ) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::NotFound); + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + priority_set( + ctx.clone(), + DeserializeStdin(WwanPrioritySetRequest { + priority: WwanPriority::Preferred, + }), + ) + .await + .unwrap(); + + assert!(section(dir.path(), "network", WWAN_INTERFACE) + .unwrap() + .contains("option metric '10'")); + assert!(section(dir.path(), "network", WAN_INTERFACE) + .unwrap() + .contains("option metric '20'")); + assert_eq!( + get(ctx).await.unwrap().uplink.unwrap().priority, + WwanPriority::Preferred + ); + } + + #[tokio::test] + async fn disconnect_restores_the_wan() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + let wireless = read(dir.path(), "wireless"); + let network = read(dir.path(), "network"); + let firewall = read(dir.path(), "firewall"); + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + disconnect(ctx.clone()).await.unwrap(); + + assert_eq!(read(dir.path(), "wireless"), wireless); + assert_eq!(read(dir.path(), "network"), network); + assert_eq!(read(dir.path(), "firewall"), firewall); + assert!(get(ctx).await.unwrap().uplink.is_none()); + } + + #[tokio::test] + async fn uplink_radios_include_luci_uplinks() { + let dir = tempfile::tempdir().unwrap(); + let disabled = + LUCI_UPLINK.replace("upstreampass'\n", "upstreampass'\n\toption disabled '1'\n"); + for (extra, expected) in [ + ("", vec![]), + (LUCI_UPLINK, vec!["radio0"]), + (disabled.as_str(), vec![]), + ] { + setup(dir.path(), &format!("{WIRELESS}{extra}"), ""); + let arena = Arena::new(); + let cfgs = parse_all(dir.path().to_path_buf(), &arena, &["wireless"]) + .await + .unwrap(); + let radios: Vec = uplink_radios(&cfgs).unwrap().into_iter().collect(); + assert_eq!(radios, expected); + } + } + + fn scanned(ssid: &str, signal: i32, encryption: serde_json::Value) -> ScanResult { + serde_json::from_value(serde_json::json!({ + "ssid": ssid, + "bssid": format!("02:00:00:00:00:{:02x}", signal.unsigned_abs()), + "channel": 6, + "signal": signal, + "encryption": encryption, + })) + .unwrap() + } + + #[test] + fn scan_security_follows_iwinfo_encryption() { + let cases = [ + ( + serde_json::json!({ "enabled": false }), + Some(WwanSecurity::Open), + ), + ( + serde_json::json!({ "enabled": true, "wpa": [2], "authentication": ["psk"], "ciphers": ["ccmp"] }), + Some(WwanSecurity::Wpa2), + ), + ( + serde_json::json!({ "enabled": true, "wpa": [1, 2], "authentication": ["psk"] }), + Some(WwanSecurity::Wpa2), + ), + ( + serde_json::json!({ "enabled": true, "wpa": [2, 3], "authentication": ["psk", "sae"] }), + Some(WwanSecurity::Wpa2Wpa3), + ), + ( + serde_json::json!({ "enabled": true, "wpa": [3], "authentication": ["sae"] }), + Some(WwanSecurity::Wpa3), + ), + ( + serde_json::json!({ "enabled": true, "wpa": [1], "authentication": ["psk"] }), + None, + ), + ( + serde_json::json!({ "enabled": true, "wpa": [2], "authentication": ["802.1x"] }), + None, + ), + ( + serde_json::json!({ "enabled": true, "wpa": [3], "authentication": ["owe"] }), + None, + ), + ( + serde_json::json!({ "enabled": true, "wep": ["open"], "ciphers": ["wep-40"] }), + None, + ), + ]; + for (encryption, expected) in cases { + let result = scanned("Net", -50, encryption.clone()); + assert_eq!(result.encryption.security(), expected, "{encryption}"); + } + } + + #[test] + fn scan_keeps_strongest_entry_per_network() { + let wpa2 = serde_json::json!({ "enabled": true, "wpa": [2], "authentication": ["psk"] }); + let networks = scan_networks(vec![ + scanned("Home", -70, wpa2.clone()), + scanned("Cafe", -60, serde_json::json!({ "enabled": false })), + scanned("Home", -40, wpa2.clone()), + scanned("", -55, wpa2.clone()), + scanned("", -80, wpa2), + ]); + let summary: Vec<(&str, Option)> = networks + .iter() + .map(|n| (n.ssid.as_str(), n.signal)) + .collect(); + assert_eq!( + summary, + vec![ + ("Home", Some(-40)), + ("", Some(-55)), + ("Cafe", Some(-60)), + ("", Some(-80)), + ] + ); + } + + #[test] + fn security_round_trips_through_uci() { + for security in [ + WwanSecurity::Open, + WwanSecurity::Wpa2, + WwanSecurity::Wpa2Wpa3, + WwanSecurity::Wpa3, + ] { + assert_eq!( + WwanSecurity::from_encryption(security.encryption()), + Some(security) + ); + } + assert_eq!( + WwanSecurity::from_encryption("psk2+ccmp"), + Some(WwanSecurity::Wpa2) + ); + assert_eq!(WwanSecurity::from_encryption("wpa2"), None); + } +} diff --git a/projects/start-wrt/backend/hotplug/99-startwrt-port-control b/projects/start-wrt/backend/hotplug/99-startwrt-port-control index 5b87df3c97..97efe1815d 100644 --- a/projects/start-wrt/backend/hotplug/99-startwrt-port-control +++ b/projects/start-wrt/backend/hotplug/99-startwrt-port-control @@ -1,5 +1,5 @@ #!/bin/sh -# Re-key SNI listeners after WAN address changes. -[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" ] && [ "$INTERFACE" = "wan" ] && { +# Re-key SNI listeners after the uplink address changes. +[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" -o "$ACTION" = "ifdown" ] && [ "$INTERFACE" = "wan" -o "$INTERFACE" = "wwan" ] && { /usr/bin/startwrt-cli published-ports wan-changed 2>/dev/null & } diff --git a/projects/start-wrt/backend/hotplug/99-startwrt-published-ports b/projects/start-wrt/backend/hotplug/99-startwrt-published-ports index 7f908a7730..1033785a06 100755 --- a/projects/start-wrt/backend/hotplug/99-startwrt-published-ports +++ b/projects/start-wrt/backend/hotplug/99-startwrt-published-ports @@ -9,6 +9,6 @@ } # WAN Whitelist/Blacklist entries are read against the WAN address to decide a # profile's hairpin; fw4's 20-firewall hook has already reloaded by this point. -[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" ] && [ "$INTERFACE" = "wan" ] && { +[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" -o "$ACTION" = "ifdown" ] && [ "$INTERFACE" = "wan" -o "$INTERFACE" = "wwan" ] && { (/usr/bin/startwrt-cli published-ports sync-hairpin && /etc/init.d/firewall reload) 2>/dev/null & } diff --git a/projects/start-wrt/backend/hotplug/99-startwrt-remote-access b/projects/start-wrt/backend/hotplug/99-startwrt-remote-access index db61dd9043..7589f6f60d 100755 --- a/projects/start-wrt/backend/hotplug/99-startwrt-remote-access +++ b/projects/start-wrt/backend/hotplug/99-startwrt-remote-access @@ -1,5 +1,5 @@ #!/bin/sh # Re-evaluate remote access firewall rules when WAN interface changes. -[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" -o "$ACTION" = "ifdown" ] && [ "$INTERFACE" = "wan" -o "$INTERFACE" = "wan6" ] && { +[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" -o "$ACTION" = "ifdown" ] && [ "$INTERFACE" = "wan" -o "$INTERFACE" = "wan6" -o "$INTERFACE" = "wwan" ] && { /usr/bin/startwrt-cli system apply-remote-access 2>/dev/null & } diff --git a/projects/start-wrt/changelog/minor-added-wireless-wan.de_DE.md b/projects/start-wrt/changelog/minor-added-wireless-wan.de_DE.md new file mode 100644 index 0000000000..f9a99671a7 --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-wireless-wan.de_DE.md @@ -0,0 +1 @@ +- **Drahtloses WAN verbindet den Router mit einem anderen WLAN für den Internetzugang**, als Reserve für den WAN-Anschluss oder an seiner Stelle. Wählen Sie auf der neuen Seite `Internet > Drahtloses WAN` ein Netzwerk aus einer Suche. Profile, veröffentlichte Ports und der Fernzugriff nutzen es genauso wie den WAN-Anschluss. Die WLAN-Seite schaltet ein Frequenzband, das den Uplink trägt, nicht mehr aus, auch wenn er in LuCI eingerichtet wurde. diff --git a/projects/start-wrt/changelog/minor-added-wireless-wan.es_ES.md b/projects/start-wrt/changelog/minor-added-wireless-wan.es_ES.md new file mode 100644 index 0000000000..f0a19827a9 --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-wireless-wan.es_ES.md @@ -0,0 +1 @@ +- **La WAN inalámbrica conecta el router a otra red Wi-Fi para acceder a Internet**, como respaldo del puerto WAN o en su lugar. Elija una red tras una búsqueda en la nueva página `Internet > WAN inalámbrica`. Los perfiles, los puertos publicados y el acceso remoto la usan igual que el puerto WAN. La página Wi-Fi ya no apaga una banda que lleva el enlace, aunque se haya configurado en LuCI. diff --git a/projects/start-wrt/changelog/minor-added-wireless-wan.fr_FR.md b/projects/start-wrt/changelog/minor-added-wireless-wan.fr_FR.md new file mode 100644 index 0000000000..7f143da31a --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-wireless-wan.fr_FR.md @@ -0,0 +1 @@ +- **Le WAN sans fil connecte le routeur à un autre réseau Wi-Fi pour accéder à Internet**, en secours du port WAN ou à sa place. Choisissez un réseau après une recherche sur la nouvelle page `Internet > WAN sans fil`. Les profils, les ports publiés et l’accès à distance l’utilisent comme le port WAN. La page Wi-Fi n’éteint plus une bande qui porte la liaison, même configurée dans LuCI. diff --git a/projects/start-wrt/changelog/minor-added-wireless-wan.md b/projects/start-wrt/changelog/minor-added-wireless-wan.md new file mode 100644 index 0000000000..176e0e1fa5 --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-wireless-wan.md @@ -0,0 +1,5 @@ +--- +release-notes: true +--- + +- **Wireless WAN connects the router to another Wi-Fi network for Internet access**, as a backup to the WAN port or in its place. Pick a network from a scan on the new `Internet > Wireless WAN` page. Profiles, published ports and remote access use it just as they use the WAN port. The Wi-Fi page no longer turns off a band that carries the uplink, including one set up in LuCI. diff --git a/projects/start-wrt/changelog/minor-added-wireless-wan.pl_PL.md b/projects/start-wrt/changelog/minor-added-wireless-wan.pl_PL.md new file mode 100644 index 0000000000..f923666b41 --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-wireless-wan.pl_PL.md @@ -0,0 +1 @@ +- **Bezprzewodowy WAN łączy router z inną siecią Wi-Fi w celu dostępu do Internetu**, jako zapas dla portu WAN lub zamiast niego. Wybierz sieć po skanowaniu na nowej stronie `Internet > Bezprzewodowy WAN`. Profile, opublikowane porty i dostęp zdalny korzystają z niego tak samo jak z portu WAN. Strona Wi-Fi nie wyłącza już pasma obsługującego łącze, także skonfigurowanego w LuCI. diff --git a/projects/start-wrt/docs/src/README.md b/projects/start-wrt/docs/src/README.md index b9fe622515..36291f556b 100644 --- a/projects/start-wrt/docs/src/README.md +++ b/projects/start-wrt/docs/src/README.md @@ -21,6 +21,7 @@ StartWRT is a router operating system designed specifically for home-based self- ## Internet - [WAN Settings](wan.md) +- [Wireless WAN](wireless-wan.md) - [Dynamic DNS](ddns.md) - [Published Ports](published-ports.md) - [Outbound VPNs](outbound-vpn.md) diff --git a/projects/start-wrt/docs/src/SUMMARY.md b/projects/start-wrt/docs/src/SUMMARY.md index 0cdfe29eae..b8cf2ef6ab 100644 --- a/projects/start-wrt/docs/src/SUMMARY.md +++ b/projects/start-wrt/docs/src/SUMMARY.md @@ -31,6 +31,7 @@ # Internet - [WAN Settings](wan.md) +- [Wireless WAN](wireless-wan.md) - [Dynamic DNS](ddns.md) - [Published Ports](published-ports.md) - [Outbound VPNs](outbound-vpn.md) diff --git a/projects/start-wrt/docs/src/overview.md b/projects/start-wrt/docs/src/overview.md index 7aa3732189..3b41882569 100644 --- a/projects/start-wrt/docs/src/overview.md +++ b/projects/start-wrt/docs/src/overview.md @@ -7,6 +7,7 @@ A device gets its profile from its [point of entry](points-of-entry.md), the way - [Inbound VPNs](inbound-vpn.md) are WireGuard servers on your router for reaching your home network from anywhere. Each one belongs to a profile, and a device connected through it gets that profile. - [Outbound VPNs](outbound-vpn.md) send a profile's internet traffic out through one or more WireGuard VPN providers, chained. When a tunnel goes down, its traffic stops rather than leaving over your home connection. - [Published ports](published-ports.md) forward ports from your router's public address to a device on your network. You can also allow a device to open its own ports. That permission is off by default and granted per device, and each port the device opens expires unless the device renews it. A StartOS server you give port-forwarding permission opens the ports its public addresses need. A separate [DNS record publishing permission](devices.md#device-detail-page) lets it publish the names of its private domains to your network. +- [Wireless WAN](wireless-wan.md) connects the router to another Wi-Fi network for Internet access, as a backup to the WAN port or in its place. The band it uses follows that network and is off while the router is not connected to it. - [Dynamic DNS](ddns.md) keeps a domain name pointed at your home connection when its address changes. - [Wi-Fi blackout schedules](wifi-schedules.md) turn the Wi-Fi radio off on a weekly timetable, and a profile's [Internet access](security-profiles.md#wan-blackout) can be blocked on a schedule of its own while its permitted LAN access stays available. Wired devices stay connected through a Wi-Fi blackout. - StartWRT [never updates on its own](updating.md). A new signed release appears in its interface, and you choose when to install it. Reflashing from a microSD card is the fallback when an update fails. diff --git a/projects/start-wrt/docs/src/wifi-schedules.md b/projects/start-wrt/docs/src/wifi-schedules.md index 2f8e0e8878..d4111a941d 100644 --- a/projects/start-wrt/docs/src/wifi-schedules.md +++ b/projects/start-wrt/docs/src/wifi-schedules.md @@ -9,7 +9,7 @@ Wi-Fi Blackout lets you disable the Wi-Fi radio on a recurring timetable. During - **Energy savings** — Turn off Wi-Fi when nobody is home during the day. > [!NOTE] -> Wi-Fi Blackout affects the radio hardware itself, not individual devices or profiles. When Wi-Fi is off, all Wi-Fi-connected devices are disconnected regardless of their profile. Ethernet-connected devices are unaffected. For per-profile time restrictions on Internet access (not Wi-Fi connectivity), use [WAN Blackout](security-profiles.md#wan-blackout) in Security Profiles. +> Wi-Fi Blackout affects the radio hardware itself, not individual devices or profiles. When Wi-Fi is off, all Wi-Fi-connected devices are disconnected regardless of their profile, and so is a [Wireless WAN](wireless-wan.md) uplink. Ethernet-connected devices are unaffected. For per-profile time restrictions on Internet access (not Wi-Fi connectivity), use [WAN Blackout](security-profiles.md#wan-blackout) in Security Profiles. ## Setting a Schedule diff --git a/projects/start-wrt/docs/src/wifi.md b/projects/start-wrt/docs/src/wifi.md index 73244b1b99..4175e7365d 100644 --- a/projects/start-wrt/docs/src/wifi.md +++ b/projects/start-wrt/docs/src/wifi.md @@ -59,7 +59,7 @@ Configure the Wi-Fi radio hardware under `Points of Entry > Wi-Fi > Settings`: - **Broadcast Separately** — Shown only when Band is "Both". When enabled, the 5 GHz band gets a separate SSID with a `-5G` suffix (e.g. `StartWRT` and `StartWRT-5G`). Useful if you want to control which band a device connects to. -- **Channel** — Separate dropdowns for each band. **Auto** (recommended) lets the router select a channel automatically. You can also select a specific channel; the dropdowns list the channels the selected country permits. **Auto** skips radar-detection (DFS) channels. You can pick one by hand, but the 5 GHz network then takes a minute or more to appear each time the router starts while it listens for radar. +- **Channel** — Separate dropdowns for each band. **Auto** (recommended) lets the router select a channel automatically. You can also select a specific channel; the dropdowns list the channels the selected country permits. **Auto** skips radar-detection (DFS) channels. You can pick one by hand, but the 5 GHz network then takes a minute or more to appear each time the router starts while it listens for radar. A band that carries a [Wireless WAN](wireless-wan.md) uplink uses the upstream network's channel instead, and cannot be turned off until the uplink is removed. - **Channel Width** — Separate dropdowns for each band setting how much of the band the network occupies: 20 or 40 MHz on 2.4 GHz, and up to 160 MHz on 5 GHz where the radio supports it. Each lists only the widths the selected channel can use in the selected country; picking a channel that cannot carry the current width switches to the widest one it can. Wider channels are faster but overlap more neighboring networks. On 2.4 GHz, a 40 MHz network starts at 20 MHz instead when a neighboring network overlaps it. diff --git a/projects/start-wrt/docs/src/wireless-wan.md b/projects/start-wrt/docs/src/wireless-wan.md new file mode 100644 index 0000000000..eaea8a66bd --- /dev/null +++ b/projects/start-wrt/docs/src/wireless-wan.md @@ -0,0 +1,40 @@ +# Wireless WAN + +Wireless WAN connects the router to another Wi-Fi network and uses it for Internet access, as a backup to the WAN port or in its place. Navigate to `Internet > Wireless WAN`. + +## How it works + +The router joins the upstream network as a Wi-Fi client on one of its bands. Your devices reach the Internet through it exactly as through the WAN port: [security profiles](security-profiles.md) that use the WAN, [published ports](published-ports.md) and remote access all follow whichever connection is carrying traffic. The router uses the DNS servers the upstream network offers, unless you have set custom servers under [WAN Settings](wan.md#dns). + +## Joining a network + +1. Choose the band to connect on, if both are on. +1. Click **Scan**. The list shows each network's name, signal strength, security and channel. +1. Click **Join** beside the network, or **Hidden network** to enter the name of one that does not broadcast it. +1. Enter the password and choose a priority, then click **Join**. + +WPA2, WPA3 and open networks are supported. WPA Enterprise and WEP networks are listed as unsupported. + +> [!WARNING] +> The band that carries the uplink belongs to it. Its Wi-Fi follows the upstream network's channel, and it is off whenever the router is not connected to that network: while it is joining, after a wrong password, or when the network is out of range. Join from a wired device or from the other band, so you do not lose access to the router. + +## Priority + +- **Backup** (default) — The WAN port carries traffic whenever it has a connection. The Wi-Fi uplink takes over when the WAN port loses its link. +- **Preferred** — The Wi-Fi uplink carries traffic whenever it is connected. The WAN port takes over when it drops. + +The router switches when a connection goes down, not when an upstream network stops reaching the Internet while staying connected. A WAN port with a [static address](wan.md#ipv4) stays up without a cable, so it never hands over to a backup uplink. + +The **Summary** shows whether the router is connected, the address the upstream network assigned, the signal, and whether the uplink is **In use** or **Standing by**. + +## Removing the uplink + +Click **Remove uplink** in the **Summary**. The router leaves the network and its Internet access depends on the WAN port alone. + +## Interactions + +- **Wi-Fi settings** — The uplink's band cannot be turned off on the [Wi-Fi](wifi.md) page while the uplink exists. Its channel setting has no effect until the uplink is removed. +- **Wi-Fi Blackout** — A [blackout window](wifi-schedules.md) turns every radio off, including the one carrying the uplink. +- **LuCI** — A Wi-Fi uplink set up in LuCI is shown here but not managed. Delete it in LuCI to manage the uplink from this page. +- **IPv6** — The Wi-Fi uplink carries IPv4. IPv6 stays on the WAN port. +- **Dynamic DNS** — [Dynamic DNS](ddns.md) publishes the WAN port's address. diff --git a/projects/start-wrt/web/src/app/app.routes.ts b/projects/start-wrt/web/src/app/app.routes.ts index 5eec1a75cd..2f96b15e73 100644 --- a/projects/start-wrt/web/src/app/app.routes.ts +++ b/projects/start-wrt/web/src/app/app.routes.ts @@ -27,6 +27,10 @@ export const routes: Routes = [ path: 'wan', loadChildren: () => import('./routes/wan'), }, + { + path: 'wwan', + loadComponent: () => import('./routes/wwan'), + }, { path: 'published-ports', loadComponent: () => import('./routes/published-ports'), diff --git a/projects/start-wrt/web/src/app/components/nav.ts b/projects/start-wrt/web/src/app/components/nav.ts index d416f3b3f3..ff5924c8b9 100644 --- a/projects/start-wrt/web/src/app/components/nav.ts +++ b/projects/start-wrt/web/src/app/components/nav.ts @@ -13,6 +13,11 @@ const MENU = { icon: '@tui.globe', link: 'wan', }, + { + name: 'Wireless WAN', + icon: '@tui.radio-tower', + link: 'wwan', + }, { name: 'Published Ports', icon: '@tui.door-open', diff --git a/projects/start-wrt/web/src/app/help/content/de.ts b/projects/start-wrt/web/src/app/help/content/de.ts index 26f140d426..d7e3bb9a36 100644 --- a/projects/start-wrt/web/src/app/help/content/de.ts +++ b/projects/start-wrt/web/src/app/help/content/de.ts @@ -407,6 +407,24 @@ Aktivieren Sie DNS over HTTPS (DoH) für verschlüsselte DNS-Abfragen. Dies verb DDNS ordnet Ihre wechselnde IP-Adresse einem festen Domänennamen zu, sodass Sie aus der Ferne auf Ihr Netzwerk zugreifen können, ohne Ihre aktuelle IP zu kennen. Erfordert ein Konto bei einem unterstützten Anbieter. Geben Sie die Zugangsdaten und den Hostnamen Ihres DDNS-Anbieters ein.`, + '/wwan': `## Drahtloses WAN + +Der Router tritt einem anderen WLAN bei und nutzt es für den Internetzugang. Geräte in Ihrem Netzwerk erreichen das Internet darüber genau wie über den WAN-Anschluss: Profile, veröffentlichte Ports und der Fernzugriff behandeln es als WAN. + +### Einem Netzwerk beitreten + +Wählen Sie ein Frequenzband, suchen Sie, und wählen Sie **Beitreten** neben einem Netzwerk oder **Verborgenes Netzwerk** für eines, das seinen Namen verbirgt. Unterstützt werden WPA2, WPA3 und offene Netzwerke, nicht aber WPA Enterprise. + +### Priorität + +- **Reserve:** Der WAN-Anschluss wird verwendet, solange er eine Verbindung hat; der WLAN-Uplink übernimmt, wenn der WAN-Anschluss seine Verbindung verliert. +- **Bevorzugt:** Der WLAN-Uplink wird verwendet, solange er verbunden ist; der WAN-Anschluss übernimmt, wenn er abbricht. + +Die Umschaltung folgt der Verbindung: Ein Upstream, der verbunden bleibt, aber das Internet nicht mehr erreicht, löst sie nicht aus. + +### Das eigene WLAN des Routers + +Das Frequenzband des Uplinks folgt dem Kanal des Upstream-Netzwerks, und sein WLAN ist aus, solange der Router nicht mit diesem Netzwerk verbunden ist, auch nach einem falschen Passwort. Treten Sie von einem kabelgebundenen Gerät oder über das andere Frequenzband bei. Ein WLAN-Sperrzeitraum, der dieses Frequenzband ausschaltet, trennt auch den Uplink.`, '/settings/activity': `## Einstellungen – Aktivität Zeigt aktuelle Anmeldeversuche und Sicherheitsereignisse an. Überwachen Sie verdächtige Aktivitäten und entfernen Sie bei Bedarf alte Einträge.`, diff --git a/projects/start-wrt/web/src/app/help/content/en.ts b/projects/start-wrt/web/src/app/help/content/en.ts index c0f5f82be9..3624ab9df9 100644 --- a/projects/start-wrt/web/src/app/help/content/en.ts +++ b/projects/start-wrt/web/src/app/help/content/en.ts @@ -407,6 +407,24 @@ Enable DNS over HTTPS (DoH) for encrypted DNS queries. This improves privacy by DDNS maps your changing IP address to a fixed domain name, allowing you to access your network remotely without knowing your current IP. Requires an account with a supported provider. Enter the credentials and hostname from your DDNS provider.`, + '/wwan': `## Wireless WAN + +The router joins another Wi-Fi network and uses it for Internet access. Devices on your network reach the Internet through it exactly as through the WAN port: profiles, published ports and remote access treat it as the WAN. + +### Joining a network + +Choose a band, scan, and select **Join** beside a network, or **Hidden network** for one that hides its name. WPA2, WPA3 and open networks are supported; WPA Enterprise networks are not. + +### Priority + +- **Backup:** the WAN port is used whenever it has a connection, and the Wi-Fi uplink takes over when the WAN port loses its link. +- **Preferred:** the Wi-Fi uplink is used whenever it is connected, and the WAN port takes over when it drops. + +Failover follows the link: an upstream that stays connected but stops reaching the Internet does not trigger it. + +### The router's own Wi-Fi + +The band that carries the uplink follows the upstream network's channel, and its Wi-Fi is off while the router is not connected to that network, including after a wrong password. Join from a wired device or from the other band. A Wi-Fi blackout window that turns that band off also disconnects the uplink.`, '/settings/activity': `## Settings – Activity View recent login attempts and security events. Monitor for suspicious activity and remove old entries as needed.`, diff --git a/projects/start-wrt/web/src/app/help/content/es.ts b/projects/start-wrt/web/src/app/help/content/es.ts index baae3532f6..68c3494a3c 100644 --- a/projects/start-wrt/web/src/app/help/content/es.ts +++ b/projects/start-wrt/web/src/app/help/content/es.ts @@ -407,6 +407,24 @@ Habilita DNS over HTTPS (DoH) para consultas DNS cifradas. Esto mejora la privac DDNS asigna tu dirección IP cambiante a un nombre de dominio fijo, permitiéndote acceder a tu red de forma remota sin conocer tu IP actual. Requiere una cuenta con un proveedor compatible. Introduce las credenciales y el nombre de host de tu proveedor de DDNS.`, + '/wwan': `## WAN inalámbrica + +El router se une a otra red Wi-Fi y la usa para acceder a Internet. Los dispositivos de su red llegan a Internet a través de ella igual que por el puerto WAN: los perfiles, los puertos publicados y el acceso remoto la tratan como la WAN. + +### Unirse a una red + +Elija una banda, busque y seleccione **Unirse** junto a una red, o **Red oculta** para una que oculta su nombre. Se admiten redes WPA2, WPA3 y abiertas; las redes WPA Enterprise no. + +### Prioridad + +- **Respaldo:** se usa el puerto WAN siempre que tenga conexión, y el enlace Wi-Fi toma el relevo cuando el puerto WAN pierde el enlace. +- **Preferida:** se usa el enlace Wi-Fi siempre que esté conectado, y el puerto WAN toma el relevo cuando se cae. + +El cambio sigue al enlace: una red superior que sigue conectada pero deja de llegar a Internet no lo activa. + +### La Wi-Fi propia del router + +La banda que lleva el enlace sigue el canal de la red superior, y su Wi-Fi está apagada mientras el router no esté conectado a esa red, también tras una contraseña incorrecta. Únase desde un dispositivo con cable o desde la otra banda. Una franja de apagado de Wi-Fi que apaga esa banda también desconecta el enlace.`, '/settings/activity': `## Ajustes – Actividad Consulta los intentos de inicio de sesión recientes y los eventos de seguridad. Vigila la actividad sospechosa y elimina las entradas antiguas según sea necesario.`, diff --git a/projects/start-wrt/web/src/app/help/content/fr.ts b/projects/start-wrt/web/src/app/help/content/fr.ts index c5e42b9911..c112bc3117 100644 --- a/projects/start-wrt/web/src/app/help/content/fr.ts +++ b/projects/start-wrt/web/src/app/help/content/fr.ts @@ -407,6 +407,24 @@ Activez le DNS over HTTPS (DoH) pour des requêtes DNS chiffrées. Cela amélior Le DDNS associe votre adresse IP changeante à un nom de domaine fixe, vous permettant d’accéder à votre réseau à distance sans connaître votre adresse IP actuelle. Nécessite un compte chez un fournisseur pris en charge. Saisissez les identifiants et le nom d’hôte de votre fournisseur DDNS.`, + '/wwan': `## WAN sans fil + +Le routeur rejoint un autre réseau Wi-Fi et l’utilise pour accéder à Internet. Les appareils de votre réseau atteignent Internet par lui exactement comme par le port WAN : les profils, les ports publiés et l’accès à distance le traitent comme le WAN. + +### Rejoindre un réseau + +Choisissez une bande, lancez une recherche, puis sélectionnez **Rejoindre** à côté d’un réseau, ou **Réseau masqué** pour un réseau qui masque son nom. Les réseaux WPA2, WPA3 et ouverts sont pris en charge ; les réseaux WPA Entreprise ne le sont pas. + +### Priorité + +- **Secours :** le port WAN est utilisé tant qu’il a une connexion, et la liaison Wi-Fi prend le relais quand le port WAN perd son lien. +- **Préféré :** la liaison Wi-Fi est utilisée tant qu’elle est connectée, et le port WAN prend le relais en cas de coupure. + +La bascule suit le lien : un réseau amont qui reste connecté mais n’atteint plus Internet ne la déclenche pas. + +### Le Wi-Fi du routeur + +La bande qui porte la liaison suit le canal du réseau amont, et son Wi-Fi est éteint tant que le routeur n’est pas connecté à ce réseau, y compris après un mauvais mot de passe. Rejoignez-le depuis un appareil filaire ou depuis l’autre bande. Une plage de coupure Wi-Fi qui éteint cette bande déconnecte aussi la liaison.`, '/settings/activity': `## Paramètres – Activité Consultez les tentatives de connexion récentes et les évènements de sécurité. Surveillez les activités suspectes et supprimez les anciennes entrées selon vos besoins.`, diff --git a/projects/start-wrt/web/src/app/help/content/pl.ts b/projects/start-wrt/web/src/app/help/content/pl.ts index 841c6d781d..434bc266f5 100644 --- a/projects/start-wrt/web/src/app/help/content/pl.ts +++ b/projects/start-wrt/web/src/app/help/content/pl.ts @@ -407,6 +407,24 @@ Włącz DNS over HTTPS (DoH) dla szyfrowanych zapytań DNS. Poprawia to prywatno DDNS mapuje Twój zmieniający się adres IP na stałą nazwę domeny, umożliwiając zdalny dostęp do Twojej sieci bez znajomości bieżącego adresu IP. Wymaga konta u obsługiwanego dostawcy. Wprowadź dane uwierzytelniające i nazwę hosta od swojego dostawcy DDNS.`, + '/wwan': `## Bezprzewodowy WAN + +Router dołącza do innej sieci Wi-Fi i używa jej do dostępu do Internetu. Urządzenia w Twojej sieci łączą się przez nią z Internetem tak samo jak przez port WAN: profile, opublikowane porty i dostęp zdalny traktują ją jak WAN. + +### Dołączanie do sieci + +Wybierz pasmo, uruchom skanowanie i wybierz **Dołącz** obok sieci albo **Ukryta sieć** dla sieci, która ukrywa swoją nazwę. Obsługiwane są sieci WPA2, WPA3 i otwarte; sieci WPA Enterprise nie są. + +### Priorytet + +- **Zapasowe:** port WAN jest używany, gdy ma połączenie, a łącze Wi-Fi przejmuje, gdy port WAN traci łącze. +- **Preferowane:** łącze Wi-Fi jest używane, gdy jest połączone, a port WAN przejmuje, gdy ono zaniknie. + +Przełączanie zależy od łącza: sieć nadrzędna, która pozostaje połączona, ale przestaje docierać do Internetu, go nie wywołuje. + +### Własne Wi-Fi routera + +Pasmo obsługujące łącze korzysta z kanału sieci nadrzędnej, a jego Wi-Fi jest wyłączone, dopóki router nie jest połączony z tą siecią, także po błędnym haśle. Dołącz z urządzenia przewodowego lub z drugiego pasma. Okno wyłączenia Wi-Fi, które wyłącza to pasmo, rozłącza również łącze.`, '/settings/activity': `## Ustawienia – Aktywność Wyświetl ostatnie próby logowania i zdarzenia bezpieczeństwa. Monitoruj podejrzaną aktywność i usuwaj stare wpisy w razie potrzeby.`, diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts index aa6721bf51..302a73b35b 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts @@ -580,4 +580,39 @@ export default { 616: 'Außerhalb des Subnetzes des Profils dieses Geräts', 617: 'Keine nutzbare Host-Adresse', 618: 'Dieses Gerät versucht, DNS-Einträge zu veröffentlichen. Erlauben Sie das Veröffentlichen von DNS-Einträgen, damit sie in Ihrem Netzwerk aufgelöst werden.', + 619: 'Drahtloses WAN', + 620: 'Verbinden Sie den Router mit einem anderen WLAN, um auf das Internet zuzugreifen, als Reserve für den WAN-Anschluss oder an seiner Stelle.', + 621: 'In LuCI wurde ein WLAN-Uplink eingerichtet. Verwalten Sie ihn dort, oder löschen Sie ihn dort, um den Uplink hier zu verwalten.', + 622: 'Netzwerkname', + 623: 'Signal', + 624: 'Frequenzband', + 625: 'Priorität', + 626: 'Solange der Router nicht mit diesem Netzwerk verbunden ist, ist sein eigenes WLAN in diesem Frequenzband aus.', + 627: 'Uplink entfernen', + 628: 'Verfügbare Netzwerke', + 629: 'Verborgenes Netzwerk', + 630: 'Suchen', + 631: 'Suchen Sie, um die WLANs aufzulisten, die dieses Frequenzband erreicht.', + 632: 'Schalten Sie das WLAN ein, um einem Netzwerk beizutreten.', + 633: 'Verbindung wird hergestellt', + 634: 'In Verwendung', + 635: 'In Bereitschaft', + 636: 'Suche läuft', + 637: 'Uplink entfernen?', + 638: 'Der Router verlässt dieses Netzwerk. Sein Internetzugang hängt dann allein vom WAN-Anschluss ab.', + 639: 'Netzwerk wird beigetreten', + 640: 'Netzwerk beigetreten', + 641: 'Uplink wird entfernt', + 642: 'Uplink entfernt', + 643: 'Netzwerk beitreten', + 644: 'Beitreten', + 645: 'Solange der Router nicht mit diesem Netzwerk verbunden ist, ist sein eigenes WLAN in diesem Frequenzband aus. Treten Sie von einem kabelgebundenen Gerät oder über das andere Frequenzband bei.', + 646: 'Muss 8 bis 63 Zeichen lang sein', + 647: 'Darf höchstens 32 Zeichen lang sein', + 648: 'Reserve: wird verwendet, solange der WAN-Anschluss keine Verbindung hat', + 649: 'Bevorzugt: wird verwendet, solange verbunden; der WAN-Anschluss übernimmt, wenn die Verbindung abbricht', + 650: 'Kanal', + 651: 'Nicht unterstützt', + 652: 'Keine Netzwerke gefunden', + 653: 'Das Frequenzband {band} trägt den WLAN-Uplink zu {ssid}. Sein WLAN folgt dem Kanal dieses Netzwerks und ist aus, solange der Uplink getrennt ist. Um dieses Frequenzband auszuschalten, entfernen Sie zuerst den Uplink.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts index 990b1732b4..dbff952d54 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts @@ -585,4 +585,39 @@ export const ENGLISH: Record = { "Outside the subnet of this device's profile": 616, 'Not a usable host address': 617, 'This device is trying to publish DNS records. Allow DNS record publishing for them to resolve on your network.': 618, + 'Wireless WAN': 619, + 'Connect the router to another Wi-Fi network for Internet access, as a backup to the WAN port or in its place.': 620, + 'A Wi-Fi uplink was set up in LuCI. Manage it there, or delete it there to manage the uplink here.': 621, + 'Network name': 622, + 'Signal': 623, + 'Band': 624, + 'Priority': 625, + 'While the router is not connected to this network, its own Wi-Fi on this band is off.': 626, + 'Remove uplink': 627, + 'Available networks': 628, + 'Hidden network': 629, + 'Scan': 630, + 'Scan to list the Wi-Fi networks this band can reach.': 631, + 'Turn on Wi-Fi to join a network.': 632, + 'Connecting': 633, + 'In use': 634, + 'Standing by': 635, + 'Scanning': 636, + 'Remove uplink?': 637, + 'The router will leave this network. Its Internet access then depends on the WAN port alone.': 638, + 'Joining network': 639, + 'Joined network': 640, + 'Removing uplink': 641, + 'Uplink removed': 642, + 'Join network': 643, + 'Join': 644, + 'While the router is not connected to this network, its own Wi-Fi on this band is off. Join from a wired device or from the other band.': 645, + 'Must be 8 to 63 characters': 646, + 'Must be at most 32 characters': 647, + 'Backup: used while the WAN port has no connection': 648, + 'Preferred: used while connected, with the WAN port taking over when it drops': 649, + 'Channel': 650, + 'Unsupported': 651, + 'No networks found': 652, + 'The {band} band carries the Wi-Fi uplink to {ssid}. Its Wi-Fi follows that network’s channel and is off while the uplink is disconnected. To turn this band off, remove the uplink first.': 653, } diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts index 1ed404e3b2..20e57bf8dd 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts @@ -580,4 +580,39 @@ export default { 616: 'Fuera de la subred del perfil de este dispositivo', 617: 'No es una dirección de host utilizable', 618: 'Este dispositivo intenta publicar registros DNS. Permita la publicación de registros DNS para que se resuelvan en su red.', + 619: 'WAN inalámbrica', + 620: 'Conecte el router a otra red Wi-Fi para acceder a Internet, como respaldo del puerto WAN o en su lugar.', + 621: 'Se configuró un enlace Wi-Fi en LuCI. Adminístrelo allí, o elimínelo allí para administrar el enlace aquí.', + 622: 'Nombre de la red', + 623: 'Señal', + 624: 'Banda', + 625: 'Prioridad', + 626: 'Mientras el router no esté conectado a esta red, su propia Wi-Fi en esta banda está apagada.', + 627: 'Quitar enlace', + 628: 'Redes disponibles', + 629: 'Red oculta', + 630: 'Buscar', + 631: 'Busque para ver las redes Wi-Fi que alcanza esta banda.', + 632: 'Active la Wi-Fi para unirse a una red.', + 633: 'Conectando', + 634: 'En uso', + 635: 'En espera', + 636: 'Buscando', + 637: '¿Quitar enlace?', + 638: 'El router dejará esta red. Su acceso a Internet dependerá entonces solo del puerto WAN.', + 639: 'Uniéndose a la red', + 640: 'Unido a la red', + 641: 'Quitando enlace', + 642: 'Enlace quitado', + 643: 'Unirse a la red', + 644: 'Unirse', + 645: 'Mientras el router no esté conectado a esta red, su propia Wi-Fi en esta banda está apagada. Únase desde un dispositivo con cable o desde la otra banda.', + 646: 'Debe tener entre 8 y 63 caracteres', + 647: 'Debe tener como máximo 32 caracteres', + 648: 'Respaldo: se usa mientras el puerto WAN no tiene conexión', + 649: 'Preferida: se usa mientras está conectada; el puerto WAN toma el relevo cuando se cae', + 650: 'Canal', + 651: 'No compatible', + 652: 'No se encontraron redes', + 653: 'La banda {band} lleva el enlace Wi-Fi a {ssid}. Su Wi-Fi sigue el canal de esa red y está apagada mientras el enlace está desconectado. Para apagar esta banda, quite primero el enlace.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts index f8d6023442..261d4e3f3c 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts @@ -580,4 +580,39 @@ export default { 616: 'En dehors du sous-réseau du profil de cet appareil', 617: "Pas une adresse d'hôte utilisable", 618: 'Cet appareil tente de publier des enregistrements DNS. Autorisez la publication d’enregistrements DNS pour qu’ils soient résolus sur votre réseau.', + 619: 'WAN sans fil', + 620: 'Connectez le routeur à un autre réseau Wi-Fi pour accéder à Internet, en secours du port WAN ou à sa place.', + 621: 'Une liaison montante Wi-Fi a été configurée dans LuCI. Gérez-la là-bas, ou supprimez-la là-bas pour la gérer ici.', + 622: 'Nom du réseau', + 623: 'Signal', + 624: 'Bande', + 625: 'Priorité', + 626: 'Tant que le routeur n’est pas connecté à ce réseau, son propre Wi-Fi sur cette bande est éteint.', + 627: 'Supprimer la liaison', + 628: 'Réseaux disponibles', + 629: 'Réseau masqué', + 630: 'Rechercher', + 631: 'Lancez une recherche pour lister les réseaux Wi-Fi que cette bande atteint.', + 632: 'Activez le Wi-Fi pour rejoindre un réseau.', + 633: 'Connexion en cours', + 634: 'Utilisé', + 635: 'En attente', + 636: 'Recherche en cours', + 637: 'Supprimer la liaison ?', + 638: 'Le routeur quittera ce réseau. Son accès à Internet dépendra alors du seul port WAN.', + 639: 'Connexion au réseau', + 640: 'Réseau rejoint', + 641: 'Suppression de la liaison', + 642: 'Liaison supprimée', + 643: 'Rejoindre le réseau', + 644: 'Rejoindre', + 645: 'Tant que le routeur n’est pas connecté à ce réseau, son propre Wi-Fi sur cette bande est éteint. Rejoignez-le depuis un appareil filaire ou depuis l’autre bande.', + 646: 'Doit comporter de 8 à 63 caractères', + 647: 'Doit comporter au plus 32 caractères', + 648: 'Secours : utilisé tant que le port WAN n’a pas de connexion', + 649: 'Préféré : utilisé tant qu’il est connecté, le port WAN prenant le relais en cas de coupure', + 650: 'Canal', + 651: 'Non pris en charge', + 652: 'Aucun réseau trouvé', + 653: 'La bande {band} porte la liaison montante Wi-Fi vers {ssid}. Son Wi-Fi suit le canal de ce réseau et est éteint tant que la liaison est déconnectée. Pour éteindre cette bande, supprimez d’abord la liaison.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts index 28d5a99328..42e7487d71 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts @@ -580,4 +580,39 @@ export default { 616: 'Poza podsiecią profilu tego urządzenia', 617: 'To nie jest użyteczny adres hosta', 618: 'To urządzenie próbuje opublikować rekordy DNS. Zezwól na publikowanie rekordów DNS, aby były rozpoznawane w Twojej sieci.', + 619: 'Bezprzewodowy WAN', + 620: 'Połącz router z inną siecią Wi-Fi, aby uzyskać dostęp do Internetu, jako zapas dla portu WAN lub zamiast niego.', + 621: 'Łącze Wi-Fi zostało skonfigurowane w LuCI. Zarządzaj nim tam albo usuń je tam, aby zarządzać łączem tutaj.', + 622: 'Nazwa sieci', + 623: 'Sygnał', + 624: 'Pasmo', + 625: 'Priorytet', + 626: 'Dopóki router nie jest połączony z tą siecią, jego własne Wi-Fi w tym paśmie jest wyłączone.', + 627: 'Usuń łącze', + 628: 'Dostępne sieci', + 629: 'Ukryta sieć', + 630: 'Skanuj', + 631: 'Skanuj, aby wyświetlić sieci Wi-Fi dostępne w tym paśmie.', + 632: 'Włącz Wi-Fi, aby dołączyć do sieci.', + 633: 'Łączenie', + 634: 'W użyciu', + 635: 'W gotowości', + 636: 'Skanowanie', + 637: 'Usunąć łącze?', + 638: 'Router opuści tę sieć. Jego dostęp do Internetu będzie wtedy zależał wyłącznie od portu WAN.', + 639: 'Dołączanie do sieci', + 640: 'Dołączono do sieci', + 641: 'Usuwanie łącza', + 642: 'Łącze usunięte', + 643: 'Dołącz do sieci', + 644: 'Dołącz', + 645: 'Dopóki router nie jest połączony z tą siecią, jego własne Wi-Fi w tym paśmie jest wyłączone. Dołącz z urządzenia przewodowego lub z drugiego pasma.', + 646: 'Musi mieć od 8 do 63 znaków', + 647: 'Może mieć najwyżej 32 znaki', + 648: 'Zapasowe: używane, gdy port WAN nie ma połączenia', + 649: 'Preferowane: używane, gdy jest połączenie; port WAN przejmuje, gdy ono zaniknie', + 650: 'Kanał', + 651: 'Nieobsługiwane', + 652: 'Nie znaleziono sieci', + 653: 'Pasmo {band} obsługuje łącze Wi-Fi do {ssid}. Jego Wi-Fi korzysta z kanału tamtej sieci i jest wyłączone, gdy łącze jest rozłączone. Aby wyłączyć to pasmo, najpierw usuń łącze.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/routes/wifi/routes/settings/index.ts b/projects/start-wrt/web/src/app/routes/wifi/routes/settings/index.ts index ecb8b264d2..bea1c67a70 100644 --- a/projects/start-wrt/web/src/app/routes/wifi/routes/settings/index.ts +++ b/projects/start-wrt/web/src/app/routes/wifi/routes/settings/index.ts @@ -1,6 +1,7 @@ import { Component, computed, effect, inject, signal } from '@angular/core' import { toSignal } from '@angular/core/rxjs-interop' import { NonNullableFormBuilder, ReactiveFormsModule } from '@angular/forms' +import { RouterLink } from '@angular/router' import { TuiResponsiveDialogService } from '@taiga-ui/addon-mobile' import { tuiMarkControlAsTouchedAndValidate, @@ -12,6 +13,7 @@ import { TuiFilterByInputPipe, TuiInput, TuiLabel, + TuiLink, TuiNotification, TuiRadio, TuiTextfield, @@ -30,11 +32,14 @@ import { PolymorpheusComponent } from '@taiga-ui/polymorpheus' import { filter, map, startWith } from 'rxjs' import { Footer } from 'src/app/components/footer' import { Form } from 'src/app/components/form' +import { BAND_LABELS } from 'src/app/routes/wwan/utils' import { ApiService, WifiConfig, WifiRegulatory, + WwanResponse, } from 'src/app/services/api/api.service' +import { fill } from 'src/app/i18n/validation-errors' import { i18nPipe } from 'src/app/i18n/i18n.pipe' import { i18nService } from 'src/app/i18n/i18n.service' import { WifiService } from '../../service' @@ -76,6 +81,12 @@ const COUNTRY_CHANGE_MAX_WIDTH = 80 } + @if (uplinkNotice(); as notice) { +
+ {{ notice }} + {{ 'Wireless WAN' | i18n }} +
+ }