diff --git a/projects/start-wrt/API_CONTRACT.md b/projects/start-wrt/API_CONTRACT.md index c7c99cce57..6e8acfc3ad 100644 --- a/projects/start-wrt/API_CONTRACT.md +++ b/projects/start-wrt/API_CONTRACT.md @@ -316,15 +316,15 @@ Internal endpoint, **not called from the frontend**. `startwrt-cli` runs it in its own process (it is not registered with `with_call_remote`), so the hook never reaches the daemon. Fired by the `/etc/hotplug.d/iface/99-startwrt-remote-access` hook (in `backend/hotplug/`) -on `ifup`, `ifupdate`, and `ifdown` of `wan` or `wan6`. +on `ifup`, `ifupdate`, and `ifdown` of `wan`, `wan6`, or `wwan`. ```rust // Request: {} // Response: null // Backend: re-applies the remote-access preference to the firewall against the // current WAN IPs, reloads the firewall, and kills WAN-side dropbear (SSH) -// sessions from sources the mode no longer admits, so they don't survive a rule -// change via conntrack ESTABLISHED state +// sessions from sources the mode no longer admits, including sessions to a +// standby uplink's address. Established sessions must not survive a tightening. ``` ### `system.set-timezone` @@ -588,7 +588,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) @@ -656,7 +656,22 @@ cloudflare script expects: `username 'Bearer'`, `domain 'host@zone'` (`'@zone'` for the apex), and `use_api_check '1'` so proxied (orange-cloud) records compare against the record's real content instead of the proxy IP. Every provider's section also gets `interface 'wan'`, binding it to hotplug -so updates fire immediately on WAN reconnect. +so updates fire immediately on WAN reconnect. The address comes from the +`wan` interface (`ip_source 'network'`), or, while a Wi-Fi uplink exists, from +`startwrt-cli wan uplink-ipv4` (`ip_source 'script'`), which prints the address +of the uplink carrying traffic. + +### `wan.uplink-ipv4` + +```rust +// Request: {} +// Response: Option +``` + +Returns the IPv4 address of the uplink carrying traffic, independent of whether +an Ethernet WAN interface is configured. Published Ports and Inbound VPNs use +it for their IPv4 endpoints. The CLI prints the bare address for ddns-scripts, +or nothing while neither uplink has one. --- @@ -1348,8 +1363,8 @@ the router currently has no global prefix (a flap to "none" never wipes rules). ``` Internal endpoint, **not called from the frontend**. Re-derives every hairpin -projection from the firewall config and the router's current WAN IPv4 -addresses (`ubus call network.interface.wan status`) — the `reflection_zone` +projection from the firewall config and the IPv4 addresses of the uplink +carrying traffic (`ubus call network.interface dump`) — the `reflection_zone` list on each published-port and automatic-forward redirect, and the LAN-side copies of each IPv6 published-port rule — and writes the config only if something changed. A profile's WAN Whitelist and Blacklist entries are read @@ -1754,6 +1769,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 is on and that an enabled client-mode `wifi-iface` +// uses, whoever configured it, is rejected with `WifiRadioCarriesUplink` (1027), +// by a preview too. ``` ### `wifi.blackout-get` @@ -2361,7 +2379,7 @@ finding marked `notice` is shown above the form instead. #[serde(rename_all = "kebab-case")] enum ConfigView { // Settings, which holds the recovery tools, is never one. - Wan, PublishedPorts, Outbound, Lan, Devices, Profiles, Ethernet, Wifi, Inbound, + Wan, PublishedPorts, Outbound, Lan, Devices, Profiles, Ethernet, Wifi, Inbound, Wwan, } #[derive(Serialize)] @@ -2375,6 +2393,7 @@ enum ConfigProblem { Absent, // a section the page requires is absent Extra, // a section beyond the one the page shows in its place Unmanaged, // a value beyond the one the page manages, left as written + Uplink, // a client-mode interface set up outside StartWRT } #[derive(Serialize)] @@ -2401,6 +2420,158 @@ struct ConfigCheck { --- +## 19. 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. + +A watcher in the daemon (`wwan::watch`, every 5 s) stops the uplink it cannot +join: it sets `wireless.wwan.disabled '1'`, which turns the band's own access +point back on, and records why in `startwrt.wwan.reason`. A new or changed +uplink stops after 30 s without connecting: `rejected` if wpa_supplicant saw +the network at −75 dBm or better since, `unreachable` otherwise. An uplink that +loses its connection stops as `rejected` once the network has refused it for +120 s while seen at that signal within the last 90 s; losing those sightings +resets the refusal timeout. An out-of-range or weak network is retried indefinitely. Sightings come from `ubus call +wpa_supplicant. control '{"command":"BSS RANGE=…"}'`. + +### `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")] +enum WwanStopReason { + /// The network was in range and did not accept the router. + Rejected, + /// The network was not found when the router tried to join it. + Unreachable, + /// Turned off outside StartWRT. + Disabled, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct WwanResponse { + /// Every `wifi-device`, e.g. { radio: "radio0", band: "2g", enabled: true }. + radios: Vec, + /// { radio, band, ssid, security, priority, stopped: Option } + uplink: Option, + /// Absent off the router, without an uplink, and while it is stopped. + state: Option, // { associated, address, signal (dBm), channel, active, subnetConflict } + /// 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`). `state.subnetConflict` +// is true while the uplink's network overlaps one on a LAN or profile interface +// in that dump. The priority reads +// back from the two interfaces' route metrics. An `encryption` on +// `wifi-iface 'wwan'` outside the four above is rejected with `CorruptedWifi`. +``` + +### `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, no control characters + security: WwanSecurity, + password: Option, // 8–63 characters, no control characters; ignored for Open + priority: WwanPriority, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +enum WwanJoinOutcome { + Connected, + /// The router stopped trying; `uplink.stopped` says why. + Stopped, + /// Undecided when the call returned. + Joining, +} +// Response: WwanJoinOutcome +// 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(), and waits up to 45 s for the station to +// authenticate or the watcher to stop it. +``` + +### `wwan.reconnect` + +```rust +// Request: {} +// Response: WwanJoinOutcome +// Backend: clears `wireless.wwan.disabled` and `startwrt.wwan`, then +// reload_system() and waits as `wwan.connect` does. `NotFound` without an +// uplink; an off or missing radio is rejected with `WifiRadioUnavailable`. +``` + +### `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 and `startwrt.wwan`, 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`**. @@ -2454,6 +2625,13 @@ The daemon (`backend/ctrl/src/bins/daemon.rs`) also serves: | `wan.dns-set` | WAN | | | `wan.ddns-get` | WAN | | | `wan.ddns-set` | WAN | | +| `wan.uplink-ipv4` | WAN | Endpoints and ddns-scripts | +| `wwan.get` | Wireless WAN | | +| `wwan.scan` | Wireless WAN | | +| `wwan.connect` | Wireless WAN | | +| `wwan.reconnect` | Wireless WAN | | +| `wwan.priority-set` | Wireless WAN | | +| `wwan.disconnect` | Wireless WAN | | | `lan.ipv4-get` | LAN | | | `lan.ipv4-set` | LAN | | | `lan.ipv6-get` | LAN | | @@ -2514,7 +2692,7 @@ The daemon (`backend/ctrl/src/bins/daemon.rs`) also serves: | `dns.injected-list` | DNS Injection | | | `config.check` | Config Check | | -**Totals:** 85 RPC methods across 18 categories, plus the HTTP/WebSocket routes +**Totals:** 92 RPC methods across 19 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..a69d345048 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, 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 dd133a68e1..e0813f3923 100644 --- a/projects/start-wrt/backend/ARCHITECTURE.md +++ b/projects/start-wrt/backend/ARCHITECTURE.md @@ -109,6 +109,11 @@ dns wan # WAN IPv4/IPv6, MAC, DNS, DDNS config +wwan # Wi-Fi uplink (Wireless WAN) + ├─ get / scan + ├─ connect / reconnect / disconnect + └─ priority-set + lan # LAN IPv4/IPv6 config published-ports # Port forwarding rules @@ -159,6 +164,16 @@ 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. + +While the uplink exists, the DDNS service reads its address from `startwrt-cli wan uplink-ipv4` (`ip_source 'script'`) in place of the `wan` interface, and the `99-startwrt-ddns` hotplug hook restarts the updater when either uplink changes. `wan.sync_ddns_source` moves the source on connect and disconnect. + +`wwan::watch` runs on its own thread for the daemon's lifetime and stops an uplink the router cannot join: `wireless.wwan.disabled '1'` with the reason in `startwrt.wwan`. A new or changed uplink has 30 s to connect. One that has connected is stopped only after 120 s of refusal by a network wpa_supplicant still sees at usable signal. `wwan.reconnect` clears the stop. + +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. @@ -313,7 +328,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/bins/daemon.rs b/projects/start-wrt/backend/ctrl/src/bins/daemon.rs index d46c906c34..9b8328cb7c 100644 --- a/projects/start-wrt/backend/ctrl/src/bins/daemon.rs +++ b/projects/start-wrt/backend/ctrl/src/bins/daemon.rs @@ -352,6 +352,20 @@ async fn inner_main() -> Result<(), Error> { tracing::error!("Failed to start IPv6 tracker: {e}"); } + // Its config reads hold a uciedit `Arena` across awaits too. + if let Err(e) = std::thread::Builder::new() + .name("wwan-watch".into()) + .spawn(|| { + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("wwan-watch runtime") + .block_on(crate::wwan::watch()); + }) + { + tracing::error!("Failed to start the Wi-Fi uplink watcher: {e}"); + } + app_state = AppState { flash_in_progress: Arc::new(AtomicBool::new(false)), }; diff --git a/projects/start-wrt/backend/ctrl/src/config_check.rs b/projects/start-wrt/backend/ctrl/src/config_check.rs index 2c778db01d..5c8ad5f5ae 100644 --- a/projects/start-wrt/backend/ctrl/src/config_check.rs +++ b/projects/start-wrt/backend/ctrl/src/config_check.rs @@ -16,7 +16,8 @@ use crate::lan::{LAN_INTERFACE, LAN_NETMASK}; use crate::prelude::*; use crate::profiles::UciProfile; use crate::utils::HandlerExtSerde; -use crate::wan::{WAN6_INTERFACE, WAN_INTERFACE}; +use crate::wan::{WAN6_INTERFACE, WAN_INTERFACE, WWAN_INTERFACE}; +use crate::wwan::{InterfaceMetric, UplinkStation, WwanSecurity}; use crate::CtrlContext; /// A page of the StartWRT UI, named by its route. Settings, which holds the recovery tools, @@ -44,6 +45,7 @@ pub enum ConfigView { Ethernet, Wifi, Inbound, + Wwan, } rpc_toolkit::reflect_ts!(ConfigView); @@ -66,6 +68,8 @@ pub enum ConfigProblem { Extra, /// A value beyond the one the page manages, left as written. Unmanaged, + /// A client-mode interface set up outside StartWRT. + Uplink, } rpc_toolkit::reflect_ts!(ConfigProblem); @@ -130,6 +134,7 @@ const ALL: &[ConfigView] = &[ Ethernet, Wifi, Inbound, + Wwan, ]; /// The pages whose requests read the file. @@ -145,6 +150,7 @@ fn file_views(config: &str) -> &'static [ConfigView] { Ethernet, Wifi, Inbound, + Wwan, ], "firewall" => &[ Wan, @@ -155,9 +161,10 @@ fn file_views(config: &str) -> &'static [ConfigView] { Ethernet, Wifi, Inbound, + Wwan, ], "dhcp" => &[Wan, PublishedPorts, Lan, Devices, Profiles], - "wireless" => &[Wifi, Profiles], + "wireless" => &[Wifi, Profiles, Wwan], "ddns" => &[Wan, PublishedPorts, Inbound], _ => ALL, } @@ -393,6 +400,9 @@ fn check_network(cfg: &Config, profiles: &BTreeSet, out: &mut Findings) _ => {} } out.read::(C, section, &views); + if matches!(name.as_deref(), Some(WAN_INTERFACE | WWAN_INTERFACE)) { + out.read::(C, section, &[Wwan]); + } } else if ty == NetworkDevice::TY { out.read::(C, section, &[Ethernet, Profiles]); } else if ty == NetworkBridgeVlan::TY { @@ -499,20 +509,36 @@ fn check_wireless(cfg: &Config, out: &mut Findings) { for section in cfg.sections.iter().filter(|s| s.ty() == WifiDevice::TY) { if section.name().is_none() { out.section(C, section, VIEWS, ConfigProblem::Unnamed); - } else if out.read::(C, section, VIEWS).is_some() { + } else if out + .read::(C, section, &[Wifi, Profiles, Wwan]) + .is_some() + { devices.extend(section.name().map(Cow::into_owned)); } } let mut access_points = BTreeSet::new(); for section in cfg.sections.iter().filter(|s| s.ty() == WifiInterface::TY) { - if section.name().is_none() { + let iface = if section.name().is_none() { out.section(C, section, VIEWS, ConfigProblem::Unnamed); - continue; + None + } else { + out.read::(C, section, VIEWS) + }; + // Saving the Wi-Fi page reads every interface as an uplink too. + let station_views: &[ConfigView] = if iface.is_some() { + &[Wifi, Wwan] + } else { + &[Wwan] + }; + if let Some(station) = out.read::(C, section, station_views) { + if station.mode == WifiMode::STA { + check_uplink(section, &station, out); + } } - let Some(iface) = out.read::(C, section, VIEWS) else { + let Some(iface) = iface else { continue; }; - if !devices.contains(&iface.device) { + if !devices.contains(&iface.device) || iface.mode == WifiMode::STA { continue; } if let Some(disabled) = option(section, "disabled") { @@ -573,6 +599,28 @@ fn check_wireless(cfg: &Config, out: &mut Findings) { } } +/// StartWRT's own uplink, and a notice on the Wi-Fi page for any other. +fn check_uplink(section: &Section, station: &UplinkStation, out: &mut Findings) { + const C: &str = "wireless"; + if section.name().as_deref() == Some(WWAN_INTERFACE) { + if WwanSecurity::from_encryption(&station.encryption).is_none() { + if let Some(encryption) = option(section, "encryption") { + out.value( + C, + section, + &[Wwan], + ConfigProblem::Unsupported, + "encryption", + encryption, + ); + } + } + } else if !station.disabled { + out.section(C, section, &[Wifi], ConfigProblem::Uplink) + .notice = true; + } +} + fn check_dhcp(cfg: &Config, profiles: &BTreeSet, out: &mut Findings) { const C: &str = "dhcp"; for section in &cfg.sections { @@ -637,7 +685,7 @@ fn check_firewall(cfg: &Config, out: &mut Findings) { } } if !wan { - out.absent(C, WAN_INTERFACE, &[Profiles]); + out.absent(C, WAN_INTERFACE, &[Profiles, Wwan]); } } @@ -713,7 +761,7 @@ mod tests { )]); assert_eq!(found.len(), 1, "{found:#?}"); assert_eq!(found[0].problem, ConfigProblem::Syntax); - assert_eq!(found[0].views, vec![Wifi, Profiles]); + assert_eq!(found[0].views, vec![Wifi, Profiles, Wwan]); let lines = stock() .into_iter() .find(|(n, _)| *n == "wireless") @@ -921,13 +969,75 @@ mod tests { problems, vec![ (Some("guest"), ConfigProblem::Extra), - (Some("wwan"), ConfigProblem::Unsupported), (None, ConfigProblem::Unnamed), ], "{found:#?}" ); } + const UPLINK: &str = "\nconfig wifi-iface 'wwan'\n\toption device 'radio0'\n\toption mode 'sta'\n\toption network 'wwan'\n\toption ssid 'Upstream'\n\toption encryption 'psk2'\n\toption key 'upstreampass'\n"; + + #[test] + fn startwrt_uplink_leaves_the_wifi_page_alone() { + let found = with(&[ + ("wireless", UPLINK), + ( + "network", + "\nconfig interface 'wwan'\n\toption proto 'dhcp'\n\toption metric '20'\n", + ), + ]); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn uplink_encryption_the_wwan_page_cannot_show() { + let found = with(&[("wireless", UPLINK.replace("'psk2'", "'wpa2'").as_str())]); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].views, vec![Wwan]); + assert_eq!(found[0].problem, ConfigProblem::Unsupported); + assert_eq!(found[0].option.as_deref(), Some("encryption")); + assert_eq!(found[0].found.as_deref(), Some("wpa2")); + assert!(!found[0].notice); + } + + #[test] + fn luci_uplink_is_a_notice_on_the_wifi_page() { + let luci = UPLINK.replace("'wwan'\n\toption device", "'wifinet2'\n\toption device"); + let found = with(&[("wireless", luci.as_str())]); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].section.as_deref(), Some("wifinet2")); + assert_eq!(found[0].views, vec![Wifi]); + assert_eq!(found[0].problem, ConfigProblem::Uplink); + assert!(found[0].notice); + + let disabled = format!("{luci}\toption disabled '1'\n"); + assert!(with(&[("wireless", disabled.as_str())]).is_empty()); + } + + #[test] + fn unreadable_station_or_metric_blocks_the_wwan_page() { + let found = with(&[( + "wireless", + format!("{UPLINK}\toption disabled 'maybe'\n").as_str(), + )]); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].views, vec![Wifi, Wwan]); + assert_eq!(found[0].option.as_deref(), Some("disabled")); + + let mut files = stock(); + let network = &mut files.iter_mut().find(|(n, _)| *n == "network").unwrap().1; + *network = network.replacen( + "config interface 'wan'\n", + "config interface 'wan'\n\toption metric 'low'\n", + 1, + ); + let files: Vec<(&str, &str)> = files.iter().map(|(n, t)| (*n, t.as_str())).collect(); + let found = findings(&files); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].views, vec![Wwan]); + assert_eq!(found[0].option.as_deref(), Some("metric")); + } + #[test] fn wifi_encryption_the_page_cannot_keep() { let mut files = stock(); 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/ethernet.rs b/projects/start-wrt/backend/ctrl/src/ethernet.rs index 6bf99882e6..03d5de6cd9 100644 --- a/projects/start-wrt/backend/ctrl/src/ethernet.rs +++ b/projects/start-wrt/backend/ctrl/src/ethernet.rs @@ -533,6 +533,7 @@ fn set_config( }, Some(DEFAULT_WAN_INTERFACE), )?; + crate::wwan::keep_wan_priority(cfgs)?; } if pending_ipv6 { cfgs["network"].append( diff --git a/projects/start-wrt/backend/ctrl/src/http_redirect.rs b/projects/start-wrt/backend/ctrl/src/http_redirect.rs index 0f861cec9b..ed23b2c855 100644 --- a/projects/start-wrt/backend/ctrl/src/http_redirect.rs +++ b/projects/start-wrt/backend/ctrl/src/http_redirect.rs @@ -81,13 +81,13 @@ async fn read_addrs() { .and_then(|out| String::from_utf8(out).ok()) .map(|json| parse_connected(&json)) .unwrap_or_default(); - let wan = tokio::task::spawn_blocking(crate::system::read_wan_ipv4_addrs) + let uplinks = tokio::task::spawn_blocking(crate::system::read_uplink_ipv4_addrs) .await .ok() .flatten(); - let local = off_wan(connected, wan.as_deref()); + let local = off_wan(connected, uplinks.as_ref().map(|u| u.all.as_slice())); let mut gate = GATE.write().unwrap_or_else(|e| e.into_inner()); - gate.wan = wan.unwrap_or_default(); + gate.wan = uplinks.map(|u| u.active).unwrap_or_default(); gate.local = local; } diff --git a/projects/start-wrt/backend/ctrl/src/lib.rs b/projects/start-wrt/backend/ctrl/src/lib.rs index 126c3512a0..5365e3d009 100644 --- a/projects/start-wrt/backend/ctrl/src/lib.rs +++ b/projects/start-wrt/backend/ctrl/src/lib.rs @@ -54,6 +54,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; @@ -426,6 +427,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/peer.rs b/projects/start-wrt/backend/ctrl/src/peer.rs index d4a5bd2597..8e13b0bda6 100644 --- a/projects/start-wrt/backend/ctrl/src/peer.rs +++ b/projects/start-wrt/backend/ctrl/src/peer.rs @@ -22,6 +22,9 @@ pub async fn describe(ip: IpAddr) -> String { async fn network_of(ip: IpAddr) -> Option { let device = route_device(ip).await?; + if crate::wwan::uplink_ifname().await.as_deref() == Some(&*device) { + return Some("WAN".into()); + } let bytes = uciedit::read_all("/etc/config", &["network", "startwrt"]) .await .ok()?; diff --git a/projects/start-wrt/backend/ctrl/src/system.rs b/projects/start-wrt/backend/ctrl/src/system.rs index 624b85a1a6..599a3dce1b 100644 --- a/projects/start-wrt/backend/ctrl/src/system.rs +++ b/projects/start-wrt/backend/ctrl/src/system.rs @@ -229,54 +229,138 @@ 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) + .map(interface_ipv4_addrs) + .unwrap_or_default() +} + +pub(crate) 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() +} + +/// 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) } -/// Every IPv4 address on the `wan` interface, in ubus order. Empty when the -/// interface is down or ubus is unavailable. +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> { + read_uplink_ipv4_addrs().map(|addrs| addrs.active) +} + +pub(crate) struct UplinkAddrs { + /// On the uplink carrying traffic. + pub(crate) active: Vec, + /// On the WAN port and the Wi-Fi uplink together. + pub(crate) all: Vec, +} + +impl UplinkAddrs { + fn from_dump(dump: &serde_json::Value) -> Self { + Self { + active: uplink_ipv4_addrs(dump), + all: every_uplink_ipv4_addr(dump), + } + } +} + +/// `None` when ubus is unavailable. +pub(crate) fn read_uplink_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(UplinkAddrs::from_dump(&dump)) +} + +fn interface_ipv4_addrs(interface: &serde_json::Value) -> Vec { + interface + .get("ipv4-address") + .and_then(|a| a.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|e| e.get("address")?.as_str()?.parse().ok()) + .collect() + }) + .unwrap_or_default() +} + +fn every_uplink_ipv4_addr(dump: &serde_json::Value) -> Vec { + dump.get("interface") + .and_then(|i| i.as_array()) + .into_iter() + .flatten() + .filter(|i| { + i.get("interface") + .and_then(|v| v.as_str()) + .is_some_and(|name| UPLINK_INTERFACES.contains(&name)) + }) + .flat_map(interface_ipv4_addrs) + .collect() } pub async fn get_wan_ipv6s() -> Result, Error> { @@ -458,12 +542,22 @@ fn remote_access_admits( }) } -/// Socket inodes of established SSH sessions to a WAN address from a source `admits` rejects. +/// Remote Access tightening revokes SSH on standby uplinks too. fn rejected_wan_ssh_inodes( table: &str, - wan: &[IpAddr], - admits: impl Fn(IpAddr) -> bool, + mode: &str, + uplinks: &UplinkAddrs, + wan_ipv6s: &[Ipv6Addr], ) -> HashSet { + let wan: Vec = uplinks + .all + .iter() + .copied() + .map(IpAddr::V4) + .chain(wan_ipv6s.iter().copied().map(IpAddr::V6)) + .collect(); + let admits = + |source| remote_access_admits(mode, source, uplinks.active.first().copied(), wan_ipv6s); table .lines() .skip(1) @@ -536,20 +630,11 @@ fn kill_dropbear_by_inodes(inodes: &HashSet) { } /// Ends WAN-side SSH sessions from sources the Remote Access mode no longer admits. -fn kill_rejected_wan_ssh_sessions(mode: &str, wan_ipv4: Option, wan_ipv6s: &[Ipv6Addr]) { - let wan: Vec = wan_ipv4 - .map(IpAddr::V4) - .into_iter() - .chain(wan_ipv6s.iter().copied().map(IpAddr::V6)) - .collect(); - if wan.is_empty() { - return; - } - let admits = |source| remote_access_admits(mode, source, wan_ipv4, wan_ipv6s); +fn kill_rejected_wan_ssh_sessions(mode: &str, uplinks: &UplinkAddrs, wan_ipv6s: &[Ipv6Addr]) { let mut inodes = HashSet::new(); for table in ["/proc/net/tcp", "/proc/net/tcp6"] { if let Ok(content) = fs::read_to_string(table) { - inodes.extend(rejected_wan_ssh_inodes(&content, &wan, &admits)); + inodes.extend(rejected_wan_ssh_inodes(&content, mode, uplinks, wan_ipv6s)); } } if !inodes.is_empty() { @@ -562,8 +647,15 @@ async fn reload_firewall(mode: &str, wan_ipv4: Option, wan_ipv6s: &[Ip let _ = crate::run_quiet_async(tokio::process::Command::new("/etc/init.d/firewall").arg("reload")) .await; - // Established sessions outlive the reload through conntrack. - kill_rejected_wan_ssh_sessions(mode, wan_ipv4, wan_ipv6s); + let uplinks = interface_dump() + .await + .as_ref() + .map(UplinkAddrs::from_dump) + .unwrap_or_else(|| UplinkAddrs { + active: wan_ipv4.into_iter().collect(), + all: wan_ipv4.into_iter().collect(), + }); + kill_rejected_wan_ssh_sessions(mode, &uplinks, wan_ipv6s); } #[instrument(skip_all)] @@ -1020,6 +1112,77 @@ 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.clone()]), (None, vec![])); + + let dump = serde_json::json!({ "interface": [lan, wan(true, 10), wwan(true, 20)] }); + assert_eq!(every_uplink_ipv4_addr(&dump), vec![wan_addr, wwan_addr]); + } + #[test] fn test_cmp_versions_prerelease() { use std::cmp::Ordering; @@ -1118,12 +1281,17 @@ mod tests { ]); let rejected = |mode: &str, wan: &str| { let wan_ip: Ipv4Addr = wan.parse().unwrap(); - let mut inodes: Vec = - rejected_wan_ssh_inodes(&table, &[IpAddr::V4(wan_ip)], |src| { - remote_access_admits(mode, src, Some(wan_ip), &[]) - }) - .into_iter() - .collect(); + let mut inodes: Vec = rejected_wan_ssh_inodes( + &table, + mode, + &UplinkAddrs { + active: vec![wan_ip], + all: vec![wan_ip], + }, + &[], + ) + .into_iter() + .collect(); inodes.sort(); inodes }; @@ -1134,9 +1302,15 @@ mod tests { ]); let wan_ip: Ipv4Addr = "10.20.0.2".parse().unwrap(); assert_eq!( - rejected_wan_ssh_inodes(&dual_stack, &[IpAddr::V4(wan_ip)], |src| { - remote_access_admits("default", src, Some(wan_ip), &[]) - }), + rejected_wan_ssh_inodes( + &dual_stack, + "default", + &UplinkAddrs { + active: vec![wan_ip], + all: vec![wan_ip], + }, + &[], + ), HashSet::from([8]) ); assert_eq!(rejected("default", "10.20.0.2"), vec![2]); @@ -1144,13 +1318,40 @@ mod tests { let public_wan = proc_table(&[("203.0.113.5", 22, "10.20.0.50", "01", 6)]); let wan_ip: Ipv4Addr = "203.0.113.5".parse().unwrap(); assert_eq!( - rejected_wan_ssh_inodes(&public_wan, &[IpAddr::V4(wan_ip)], |src| { - remote_access_admits("default", src, Some(wan_ip), &[]) - }), + rejected_wan_ssh_inodes( + &public_wan, + "default", + &UplinkAddrs { + active: vec![wan_ip], + all: vec![wan_ip], + }, + &[], + ), HashSet::from([6]) ); } + #[test] + fn remote_access_tightening_revokes_both_ipv4_uplinks() { + let table = proc_table(&[ + ("10.20.0.2", 22, "10.20.0.50", "01", 1), + ("192.168.43.27", 22, "192.168.43.50", "01", 2), + ("192.168.0.1", 22, "192.168.0.50", "01", 3), + ]); + for (wan_metric, wwan_metric) in [(10, 20), (20, 10)] { + let dump = serde_json::json!({ "interface": [ + iface("wan", true, wan_metric, "10.20.0.2", true), + iface("wwan", true, wwan_metric, "192.168.43.27", true), + ] }); + let uplinks = UplinkAddrs::from_dump(&dump); + assert_eq!( + rejected_wan_ssh_inodes(&table, "never", &uplinks, &[]), + HashSet::from([1, 2]) + ); + assert!(rejected_wan_ssh_inodes(&table, "always", &uplinks, &[]).is_empty()); + } + } + #[test] fn test_rejected_wan_ssh_inodes_ipv6() { let table = proc_table(&[ @@ -1158,12 +1359,14 @@ mod tests { ("fd00::1", 22, "2001:db8::5", "01", 2), ]); let rejected = |wan_ipv6s: &[Ipv6Addr]| { - let wan: Vec = vec!["fd00::1".parse().unwrap()]; - let mut inodes: Vec = rejected_wan_ssh_inodes(&table, &wan, |src| { - remote_access_admits("default", src, None, wan_ipv6s) - }) - .into_iter() - .collect(); + let uplinks = UplinkAddrs { + active: vec![], + all: vec![], + }; + let mut inodes: Vec = + rejected_wan_ssh_inodes(&table, "default", &uplinks, wan_ipv6s) + .into_iter() + .collect(); inodes.sort(); inodes }; diff --git a/projects/start-wrt/backend/ctrl/src/wan.rs b/projects/start-wrt/backend/ctrl/src/wan.rs index ebe32a3bef..335f50316c 100644 --- a/projects/start-wrt/backend/ctrl/src/wan.rs +++ b/projects/start-wrt/backend/ctrl/src/wan.rs @@ -1,4 +1,4 @@ -use rpc_toolkit::{from_fn_async_local, ParentHandler}; +use rpc_toolkit::{from_fn_async_local, HandlerExt, ParentHandler}; use serde::{Deserialize, Serialize}; use uciedit::openwrt::{ DdnsService, InterfaceProto, NetworkDevice, NetworkInterface, UciSystemDns, @@ -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"; @@ -252,6 +256,15 @@ pub fn wan() -> ParentHandler { "ipv6-set", from_fn_async_local(ipv6_set::).with_display_serializable(), ) + .subcommand( + "uplink-ipv4", + from_fn_async_local(uplink_ipv4::).with_custom_display_fn::(|_, ip| { + if let Some(ip) = ip { + println!("{ip}"); + } + Ok(()) + }), + ) .subcommand( "mac-get", from_fn_async_local(mac_get::).with_display_serializable(), @@ -918,6 +931,115 @@ pub async fn dns_get(ctx: C) -> Result { } } +/// Prints the address DDNS publishes. +const UPLINK_IPV4_COMMAND: &str = "/usr/bin/startwrt-cli wan uplink-ipv4"; + +/// Where ddns-scripts reads the address it publishes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DdnsSource { + /// The WAN port's address. + WanPort, + /// The address of the uplink carrying traffic. + ActiveUplink, +} + +impl DdnsSource { + fn of(cfgs: &uciedit::Configs) -> Self { + let wifi_uplink = cfgs["network"] + .sections + .iter() + .any(|s| s.ty() == NetworkInterface::TY && s.name().as_deref() == Some(WWAN_INTERFACE)); + if wifi_uplink { + DdnsSource::ActiveUplink + } else { + DdnsSource::WanPort + } + } + + fn ip_source(self) -> &'static str { + match self { + DdnsSource::WanPort => "network", + DdnsSource::ActiveUplink => "script", + } + } + + fn ip_network(self) -> Option { + (self == DdnsSource::WanPort).then(|| WAN_INTERFACE.to_string()) + } + + fn ip_script(self) -> Option { + (self == DdnsSource::ActiveUplink).then(|| UPLINK_IPV4_COMMAND.to_string()) + } +} + +/// The address source of a DDNS service, written without touching its other options. +#[derive(Debug, TypedSection, Default)] +#[uci(ty = "service")] +struct DdnsAddressSource { + #[uci(default)] + enabled: Option, + #[uci(default)] + ip_source: Option, + #[uci(default)] + ip_network: Option, + #[uci(default)] + ip_script: Option, +} + +/// Points DDNS at the uplink that carries traffic. True when an enabled service changed. +pub(crate) fn sync_ddns_source(cfgs: &mut uciedit::Configs) -> Result { + let source = DdnsSource::of(cfgs); + let mut changed = false; + for section in &mut cfgs["ddns"].sections { + if section.name().as_deref() != Some(DDNS_SECTION) { + continue; + } + if let Some(mut service) = section.get_typed::()? { + if service.ip_source.as_deref() == Some(source.ip_source()) { + continue; + } + service.ip_source = Some(source.ip_source().to_string()); + service.ip_network = source.ip_network(); + service.ip_script = source.ip_script(); + changed |= service.enabled.as_deref() == Some("1"); + section.set(&service)?; + } + } + Ok(changed) +} + +/// The active uplink address is available without an Ethernet WAN interface. +pub async fn uplink_ipv4(ctx: C) -> Result, Error> { + Ok(ctx.wan_ipv4_addrs().first().map(ToString::to_string)) +} + +/// 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 +1070,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 @@ -1129,21 +1227,23 @@ pub async fn ddns_set( let mut retries = 4; loop { let arena = Arena::new(); - let mut cfgs = parse_all(ctx.uci_root(), &arena, &["ddns"]).await?; + let mut cfgs = parse_all(ctx.uci_root(), &arena, &["ddns", "network"]).await?; let ddns_idx = cfgs["ddns"] .sections .iter() .position(|s| s.name().as_deref() == Some(DDNS_SECTION)); + let source = DdnsSource::of(&cfgs); let new_svc = DdnsService { enabled: Some(if req.enabled { "1" } else { "0" }.to_string()), service_name: Some(provider_to_service(&req.provider).to_string()), - ip_source: Some("network".to_string()), - ip_network: Some("wan".to_string()), + ip_source: Some(source.ip_source().to_string()), + ip_network: source.ip_network(), + ip_script: source.ip_script(), // Hotplug binding: re-run the update as soon as the WAN bounces // instead of waiting for the daemon's next check interval - interface: Some("wan".to_string()), + interface: Some(WAN_INTERFACE.to_string()), use_api_check: if req.provider == DdnsProvider::Cloudflare { Some("1".to_string()) } else { @@ -1234,6 +1334,43 @@ mod tests { } } + #[tokio::test] + async fn active_uplink_endpoint_needs_no_wan_port_config() { + #[derive(Clone)] + struct UplinkOnlyContext(PathBuf); + + impl Context for UplinkOnlyContext { + fn runtime(&self) -> Option> { + None + } + } + + impl CtrlContext for UplinkOnlyContext { + fn uci_root(&self) -> PathBuf { + self.0.clone() + } + fn effectful(&self) -> bool { + false + } + fn wan_ipv4_addrs(&self) -> Vec { + vec!["192.168.43.27".parse().unwrap()] + } + } + + let dir = tempfile::tempdir().unwrap(); + let ctx = UplinkOnlyContext(dir.path().to_path_buf()); + assert_eq!( + uplink_ipv4(ctx).await.unwrap(), + Some("192.168.43.27".into()) + ); + assert_eq!( + uplink_ipv4(TestContext(dir.path().to_path_buf())) + .await + .unwrap(), + None + ); + } + /// The wan6 proto and `auto` option as written to disk. async fn wan6_on_disk(dir: &std::path::Path) -> Option<(InterfaceProto, Option)> { let arena = Arena::new(); @@ -1674,6 +1811,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..91b22dbcf8 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, device, radio) in find_relevant_with_radios(cfgs, radios)? { + if !radio.enabled && !device.disabled && 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,116 @@ 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); + + let wireless = std::fs::read_to_string(dir.path().join("wireless")).unwrap(); + std::fs::write( + dir.path().join("wireless"), + wireless.replacen( + "\toption channel 'auto'\n", + "\toption channel 'auto'\n\toption disabled '1'\n", + 1, + ), + ) + .unwrap(); + let arena = Arena::new(); + let cfgs = parse_all(dir.path().to_path_buf(), &arena, &["wireless"]) + .await + .unwrap(); + check_uplink_radios(&cfgs, &radio(false)).unwrap(); + } + + #[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() + .replacen( + "\toption channel '1'\n\toption disabled '1'\n", + "\toption channel '1'\n", + 1, + ); + 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..3a7a4c8cfd --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/wwan.rs @@ -0,0 +1,2479 @@ +//! 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. +//! +//! The band carrying the uplink has its own Wi-Fi off while the uplink is not +//! connected. [`watch`] stops an uplink the router cannot join, which brings +//! that Wi-Fi back. + +use std::cell::Cell; +use std::collections::{BTreeMap, BTreeSet}; +use std::time::{Duration, Instant}; + +use ipnet::Ipv4Net; +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; + +/// How long a new or changed uplink has to connect. +const JOIN_TIMEOUT: Duration = Duration::from_secs(30); +/// How long a network in range may refuse the router. +const REFUSED_TIMEOUT: Duration = Duration::from_secs(120); +/// How old a sighting may be and still put the network in range. +const SEEN_RECENTLY: Duration = Duration::from_secs(90); +/// Weaker signal counts as out of range. +const USABLE_SIGNAL_DBM: i32 = -75; +const WATCH_INTERVAL: Duration = Duration::from_secs(5); +/// The `startwrt` section that records why the uplink was stopped. +const STOP_SECTION: &str = "wwan"; + +/// A client-mode Wi-Fi interface, read without the access-point options. +#[derive(Debug, Clone, TypedSection)] +#[uci(ty = "wifi-iface")] +pub(crate) struct UplinkStation { + device: String, + #[uci(default)] + pub(crate) mode: WifiMode, + #[uci(default)] + network: Option, + #[uci(default)] + ssid: String, + #[uci(default_value = "none".to_string())] + pub(crate) encryption: String, + #[uci(default)] + key: Option, + #[uci(default_value = false)] + pub(crate) disabled: bool, +} + +/// The `disabled` option of a `wifi-iface`, written without touching its other options. +#[derive(Debug, Default, TypedSection)] +#[uci(ty = "wifi-iface")] +struct StationSwitch { + #[uci(default_value = false)] + disabled: bool, +} + +/// Why StartWRT stopped the uplink. +#[derive(Debug, Default, TypedSection)] +#[uci(ty = "wwan")] +struct UplinkStop { + #[uci(default)] + reason: Option, +} + +/// 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")] +pub(crate) 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. + pub(crate) 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); + +/// Why the router is not trying to join the uplink's network. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, visit_rs::VisitVariants)] +#[serde(rename_all = "camelCase")] +pub enum WwanStopReason { + /// The network was in range and did not accept the router. + Rejected, + /// The network was not found when the router tried to join it. + Unreachable, + /// Turned off outside StartWRT. + Disabled, +} +rpc_toolkit::reflect_ts!(WwanStopReason); + +impl WwanStopReason { + fn as_uci(self) -> &'static str { + match self { + WwanStopReason::Rejected => "rejected", + WwanStopReason::Unreachable => "unreachable", + WwanStopReason::Disabled => "disabled", + } + } + + fn from_uci(reason: &str) -> Self { + match reason { + "rejected" => WwanStopReason::Rejected, + "unreachable" => WwanStopReason::Unreachable, + _ => WwanStopReason::Disabled, + } + } + + fn detail(self) -> &'static str { + match self { + WwanStopReason::Rejected => "the network did not accept the router", + WwanStopReason::Unreachable => "the network was not found", + WwanStopReason::Disabled => "the uplink was turned off", + } + } +} + +#[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, + /// Set while the router is not trying to join the network. + pub stopped: Option, +} +rpc_toolkit::reflect_ts!(WwanUplink); + +/// How a join ended. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, visit_rs::VisitVariants)] +#[serde(rename_all = "camelCase")] +pub enum WwanJoinOutcome { + Connected, + /// The router stopped trying; the uplink's `stopped` says why. + Stopped, + /// Undecided when the call returned. + Joining, +} +rpc_toolkit::reflect_ts!(WwanJoinOutcome); + +/// 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, + /// Whether the joined network uses the address range of one of the router's own networks. + pub subnet_conflict: 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( + "reconnect", + from_fn_async_local(reconnect::).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) +} + +/// Gives a `wan` interface created beside the uplink the metric that keeps the priority. +pub(crate) fn keep_wan_priority(cfgs: &mut Configs) -> Result<(), Error> { + let Some(wwan) = interface_metric(cfgs, WWAN_INTERFACE)? else { + return Ok(()); + }; + let metric = match wwan { + PREFERRED_METRIC => BACKUP_METRIC, + _ => PREFERRED_METRIC, + }; + 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 = Some(metric); + section.set(&iface)?; + } + } + } + Ok(()) +} + +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 is_stop_section(section: &uciedit::Section) -> bool { + section.ty() == UplinkStop::TY && section.name().as_deref() == Some(STOP_SECTION) +} + +fn stop_reason(cfgs: &Configs) -> Result { + for section in cfgs["startwrt"] + .sections + .iter() + .filter(|s| is_stop_section(s)) + { + if let Some(stop) = section.get_typed::()? { + return Ok(stop + .reason + .as_deref() + .map_or(WwanStopReason::Disabled, WwanStopReason::from_uci)); + } + } + Ok(WwanStopReason::Disabled) +} + +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::CorruptedWifi, + ) + })?; + 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)?, + stopped: station.disabled.then(|| stop_reason(cfgs)).transpose()?, + }); + } + 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() +} + +/// The IPv4 networks on each interface of a `network.interface dump`, by interface name. +fn interface_networks(dump: &serde_json::Value) -> Vec<(&str, Ipv4Net)> { + dump.get("interface") + .and_then(|i| i.as_array()) + .into_iter() + .flatten() + .filter_map(|i| { + Some(( + i.get("interface")?.as_str()?, + i.get("ipv4-address")?.as_array()?, + )) + }) + .flat_map(|(name, addresses)| { + addresses.iter().filter_map(move |a| { + let address = a.get("address")?.as_str()?.parse().ok()?; + let mask = u8::try_from(a.get("mask")?.as_u64()?).ok()?; + Some((name, Ipv4Net::new(address, mask).ok()?)) + }) + }) + .collect() +} + +/// Whether the uplink's network overlaps one the router serves. +fn subnet_conflict(dump: &serde_json::Value) -> bool { + let networks = interface_networks(dump); + let is_uplink = |name: &str| matches!(name, WAN_INTERFACE | WWAN_INTERFACE | "loopback"); + networks + .iter() + .filter(|(name, _)| *name == WWAN_INTERFACE) + .any(|(_, uplink)| { + networks.iter().any(|(name, net)| { + !is_uplink(name) + && (net.contains(&uplink.network()) || uplink.contains(&net.network())) + }) + }) +} + +async fn read_state() -> WwanState { + let mut state = WwanState::default(); + if let Some(dump) = crate::system::interface_dump().await { + state.address = interface_networks(&dump) + .into_iter() + .find(|(name, _)| *name == WWAN_INTERFACE) + .map(|(_, net)| net.addr().to_string()); + state.subnet_conflict = subnet_conflict(&dump); + } + let radios = wireless_status().await.unwrap_or_default(); + if let Some(ifname) = ifname_of(&radios, WWAN_INTERFACE) { + state.associated = associated(ifname).await; + if let Some(info) = ubus_call( + "iwinfo", + "info", + Some(serde_json::json!({ "device": ifname })), + ) + .await + { + 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 +} + +/// A station's carrier is up once it authenticates; iwinfo's bssid is its own address. +async fn associated(ifname: &str) -> bool { + tokio::fs::read_to_string(format!("/sys/class/net/{ifname}/operstate")) + .await + .is_ok_and(|s| s.trim() == "up") +} + +/// The kernel interface of StartWRT's uplink, while netifd has one up. +pub(crate) async fn uplink_ifname() -> Option { + let status = wireless_status().await?; + ifname_of(&status, WWAN_INTERFACE).map(String::from) +} + +async fn uplink_associated() -> bool { + let status = wireless_status().await.unwrap_or_default(); + match ifname_of(&status, WWAN_INTERFACE) { + Some(ifname) => associated(ifname).await, + None => false, + } +} + +// ── Sightings ─────────────────────────────────────────────── + +/// One entry of the station's scan results for the uplink's network. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Sighting { + /// Since the network was last seen. + age: Duration, + /// Signal strength in dBm. + level: i32, +} + +/// The id, level, age and ssid of each entry, delimited. +const BSS_MASK: u32 = 0x1 | 0x80 | 0x200 | 0x1000 | 0x20000; +/// Bounds the pages read from one station. +const MAX_BSS_PAGES: usize = 8; + +/// wpa_supplicant's escaping of an SSID in its control replies. +fn wpa_ssid_text(ssid: &str) -> String { + let mut text = String::new(); + for &byte in ssid.as_bytes() { + match byte { + b'"' => text.push_str("\\\""), + b'\\' => text.push_str("\\\\"), + 0x1b => text.push_str("\\e"), + b'\n' => text.push_str("\\n"), + b'\r' => text.push_str("\\r"), + b'\t' => text.push_str("\\t"), + 32..=126 => text.push(byte as char), + _ => text.push_str(&format!("\\x{byte:02x}")), + } + } + text +} + +/// One page of `BSS RANGE` output: the sightings of `ssid`, the last id read, +/// and whether the page reached the final entry. +fn parse_bss_page(page: &str, ssid: &str) -> (Vec, Option, bool) { + let wanted = wpa_ssid_text(ssid); + let mut sightings = Vec::new(); + let mut last_id = None; + let mut entry: BTreeMap<&str, &str> = BTreeMap::new(); + let mut complete = false; + for line in page.lines() { + if line == "====" || line == "####" { + if let Some(id) = entry.get("id").and_then(|v| v.parse().ok()) { + last_id = Some(id); + } + let level = entry.get("level").and_then(|v| v.parse().ok()); + let age = entry.get("age").and_then(|v| v.parse().ok()); + if let (Some(level), Some(age), Some(true)) = + (level, age, entry.get("ssid").map(|s| *s == wanted)) + { + sightings.push(Sighting { + age: Duration::from_secs(age), + level, + }); + } + entry.clear(); + complete = line == "####"; + } else if let Some((key, value)) = line.split_once('=') { + entry.insert(key, value); + } + } + (sightings, last_id, complete) +} + +/// Where the station's wpa_supplicant last saw `ssid`; empty when it is not running. +async fn sightings(ifname: &str, ssid: &str) -> Vec { + let object = format!("wpa_supplicant.{ifname}"); + let mut found = Vec::new(); + let mut from = 0; + // A reply holds 4 KiB, so a crowded band takes several pages. + for _ in 0..MAX_BSS_PAGES { + let command = format!("BSS RANGE={from}- MASK={BSS_MASK:x}"); + let Some(reply) = ubus_call( + &object, + "control", + Some(serde_json::json!({ "command": command })), + ) + .await + else { + break; + }; + let page = reply + .get("result") + .and_then(|v| v.as_str()) + .unwrap_or_default(); + let (mut seen, last_id, complete) = parse_bss_page(page, ssid); + found.append(&mut seen); + match last_id { + Some(id) if !complete => from = id + 1, + _ => break, + } + } + found +} + +// ── 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.ssid.contains(char::is_control) { + return Err(Error::new( + eyre!("network name must not contain control characters"), + ErrorKind::InvalidValue, + )); + } + if req.security != WwanSecurity::Open { + let password = req.password.as_deref().unwrap_or_default(); + if !(crate::wifi::MIN_PSK_LEN..=crate::wifi::MAX_PSK_LEN).contains(&password.len()) { + return Err(Error::new( + eyre!( + "password must be {} to {} characters", + crate::wifi::MIN_PSK_LEN, + crate::wifi::MAX_PSK_LEN + ), + ErrorKind::InvalidValue, + )); + } + if password.contains(char::is_control) { + return Err(Error::new( + eyre!("password must not contain control characters"), + 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)); + } + clear_stop(cfgs); +} + +fn clear_stop(cfgs: &mut Configs) { + cfgs["startwrt"].sections.retain(|s| !is_stop_section(s)); +} + +/// The uplink's settings the router joins with. A change to any is a new join. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Attempted { + device: String, + ssid: String, + encryption: String, + key: Option, +} + +impl From for Attempted { + fn from(station: UplinkStation) -> Self { + Attempted { + device: station.device, + ssid: station.ssid, + encryption: station.encryption, + key: station.key, + } + } +} + +/// StartWRT's uplink, unless it is absent or stopped. +fn running_uplink(cfgs: &Configs) -> Result, Error> { + Ok(stations(cfgs)? + .into_iter() + .find(|(name, _)| name.as_deref() == Some(WWAN_INTERFACE)) + .filter(|(_, station)| !station.disabled) + .map(|(_, station)| station.into())) +} + +fn set_station_disabled(cfgs: &mut Configs, disabled: bool) -> Result<(), Error> { + for section in &mut cfgs["wireless"].sections { + if section.name().as_deref() == Some(WWAN_INTERFACE) { + if let Some(mut station) = section.get_typed::()? { + station.disabled = disabled; + section.set(&station)?; + } + } + } + Ok(()) +} + +/// False when the uplink is no longer the one that was attempted. +fn apply_stop( + cfgs: &mut Configs, + attempted: &Attempted, + reason: WwanStopReason, +) -> Result { + if running_uplink(cfgs)?.as_ref() != Some(attempted) { + return Ok(false); + } + set_station_disabled(cfgs, true)?; + clear_stop(cfgs); + cfgs["startwrt"].append( + &UplinkStop { + reason: Some(reason.as_uci().to_string()), + }, + Some(STOP_SECTION), + )?; + Ok(true) +} + +fn apply_reconnect(cfgs: &mut Configs) -> Result<(), Error> { + let station = stations(cfgs)? + .into_iter() + .find(|(name, _)| name.as_deref() == Some(WWAN_INTERFACE)) + .map(|(_, station)| station) + .ok_or_else(|| Error::new(eyre!("no Wi-Fi uplink"), ErrorKind::NotFound))?; + if radios(cfgs)? + .get(&station.device) + .map_or(true, |d| d.disabled) + { + return Err(Error::new( + eyre!("radio {} is off or missing", station.device), + ErrorKind::WifiRadioUnavailable, + )); + } + set_station_disabled(cfgs, false)?; + clear_stop(cfgs); + Ok(()) +} + +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 and re-applies on a config conflict. False when `apply` declined to write. +async fn update( + ctx: &C, + apply: impl Fn(&mut Configs) -> Result, +) -> Result { + let mut retries = 4; + loop { + let arena = Arena::new(); + let mut cfgs = parse_all( + ctx.uci_root(), + &arena, + &["wireless", "network", "firewall", "startwrt", "ddns"], + ) + .await?; + if !apply(&mut cfgs)? { + return Ok(false); + } + 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) => return Err(err.into()), + Ok(()) => return Ok(true), + } + } +} + +/// Writes, logs the outcome, and reloads the network and a DDNS service whose source moved. +async fn write( + ctx: &C, + action: &str, + summary: &str, + apply: impl Fn(&mut Configs) -> Result<(), Error>, +) -> Result<(), Error> { + let ddns_moved = Cell::new(false); + let written = update(ctx, |cfgs| { + apply(cfgs)?; + ddns_moved.set(crate::wan::sync_ddns_source(cfgs)?); + Ok(true) + }) + .await; + if let Err(err) = written { + crate::activity::log("wwan", action, false, summary, Some(&err.to_string())); + return Err(err); + } + crate::activity::log("wwan", action, true, summary, None); + if ctx.effectful() { + profiles::reload_system().await?; + if ddns_moved.get() { + let _ = crate::run_quiet_async( + tokio::process::Command::new("/etc/init.d/ddns").arg("restart"), + ) + .await; + } + } + Ok(()) +} + +/// Waits for the watcher to settle a join. +async fn await_join(ctx: &C) -> Result { + if !ctx.effectful() { + return Ok(WwanJoinOutcome::Joining); + } + // The watcher notices the change within one interval and decides by JOIN_TIMEOUT. + let deadline = Instant::now() + JOIN_TIMEOUT + WATCH_INTERVAL * 3; + while Instant::now() < deadline { + tokio::time::sleep(Duration::from_secs(1)).await; + let stopped = { + let arena = Arena::new(); + let cfgs = + parse_all(ctx.uci_root(), &arena, &["wireless", "network", "startwrt"]).await?; + get_config(&cfgs)?.uplink.map(|u| u.stopped.is_some()) + }; + match stopped { + None => return Ok(WwanJoinOutcome::Joining), + Some(true) => return Ok(WwanJoinOutcome::Stopped), + Some(false) if uplink_associated().await => return Ok(WwanJoinOutcome::Connected), + Some(false) => {} + } + } + Ok(WwanJoinOutcome::Joining) +} + +// ── 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", "startwrt"]).await?; + get_config(&cfgs)? + }; + if ctx.effectful() && res.uplink.as_ref().is_some_and(|u| u.stopped.is_none()) { + 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 { + write( + &ctx, + "added", + &format!("Added Wi-Fi uplink {}", req.ssid), + |cfgs| apply_connect(cfgs, &req), + ) + .await?; + await_join(&ctx).await +} + +#[instrument(skip_all)] +pub async fn reconnect(ctx: C) -> Result { + write(&ctx, "retried", "Retried Wi-Fi uplink", apply_reconnect).await?; + await_join(&ctx).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 +} + +// ── Watcher ───────────────────────────────────────────────── + +#[derive(Debug, PartialEq, Eq)] +enum Verdict { + Wait, + Joined, + /// Gives up, during a join or after one. + Stop { + reason: WwanStopReason, + joining: bool, + }, +} + +struct Attempt { + uplink: Attempted, + /// Added or changed while the watcher ran, and not connected since. + joining: bool, + /// When the router last had the connection, or began this attempt. + since: Instant, + /// When the network was last seen with usable signal after `since`. + seen: Option, + refused_since: Option, +} + +/// An out-of-range interval does not count toward the refusal timeout. +#[derive(Default)] +struct Tracker { + started: bool, + attempt: Option, +} + +impl Tracker { + /// No uplink is running. + fn idle(&mut self) { + self.started = true; + self.attempt = None; + } + + fn observe( + &mut self, + uplink: Attempted, + now: Instant, + connected: bool, + sightings: &[Sighting], + ) -> Verdict { + let joining = self.started; + self.started = true; + let attempt = match &mut self.attempt { + Some(attempt) if attempt.uplink == uplink => attempt, + slot => slot.insert(Attempt { + uplink, + joining, + since: now, + seen: None, + refused_since: None, + }), + }; + if connected { + let joined = attempt.joining; + attempt.joining = false; + attempt.since = now; + attempt.seen = None; + attempt.refused_since = None; + return if joined { + Verdict::Joined + } else { + Verdict::Wait + }; + } + for sighting in sightings { + let at = now.checked_sub(sighting.age).unwrap_or(now); + if sighting.level >= USABLE_SIGNAL_DBM && at > attempt.since { + attempt.seen = Some(attempt.seen.map_or(at, |seen| seen.max(at))); + } + } + let elapsed = now.saturating_duration_since(attempt.since); + if attempt.joining { + if elapsed >= JOIN_TIMEOUT { + let reason = if attempt.seen.is_some() { + WwanStopReason::Rejected + } else { + WwanStopReason::Unreachable + }; + return Verdict::Stop { + reason, + joining: true, + }; + } + } else if attempt + .seen + .is_some_and(|at| now.saturating_duration_since(at) <= SEEN_RECENTLY) + { + let refused_since = attempt.refused_since.get_or_insert(now); + if now.saturating_duration_since(*refused_since) >= REFUSED_TIMEOUT { + return Verdict::Stop { + reason: WwanStopReason::Rejected, + joining: false, + }; + } + } else { + attempt.refused_since = None; + } + Verdict::Wait + } +} + +/// Stops the uplink when the router cannot join its network, for the daemon's lifetime. +pub async fn watch() { + let ctx = crate::ServerContext::default(); + let mut tracker = Tracker::default(); + let mut ticks = tokio::time::interval(WATCH_INTERVAL); + let mut failure = None; + loop { + ticks.tick().await; + let failed = watch_once(&ctx, &mut tracker) + .await + .err() + .map(|e| e.to_string()); + if let Some(e) = failed.as_ref().filter(|e| failure.as_ref() != Some(*e)) { + tracing::warn!("Wi-Fi uplink watch failed: {e}"); + } + failure = failed; + } +} + +async fn watch_once(ctx: &C, tracker: &mut Tracker) -> Result<(), Error> { + let uplink = { + let arena = Arena::new(); + let cfgs = parse_all(ctx.uci_root(), &arena, &["wireless"]).await?; + running_uplink(&cfgs)? + }; + let Some(uplink) = uplink else { + tracker.idle(); + return Ok(()); + }; + let status = wireless_status().await.unwrap_or_default(); + let ifname = ifname_of(&status, WWAN_INTERFACE); + let connected = match ifname { + Some(ifname) => associated(ifname).await, + None => false, + }; + let seen = match ifname { + Some(ifname) if !connected => sightings(ifname, &uplink.ssid).await, + _ => Vec::new(), + }; + match tracker.observe(uplink.clone(), Instant::now(), connected, &seen) { + Verdict::Wait => {} + Verdict::Joined => crate::activity::log( + "wwan", + "joined", + true, + &format!("Joined Wi-Fi uplink {}", uplink.ssid), + None, + ), + Verdict::Stop { reason, joining } => { + if update(ctx, |cfgs| apply_stop(cfgs, &uplink, reason)).await? { + let summary = if joining { + format!("Couldn't join Wi-Fi uplink {}", uplink.ssid) + } else { + format!("Stopped Wi-Fi uplink {}", uplink.ssid) + }; + crate::activity::log("wwan", "stopped", false, &summary, Some(reason.detail())); + if ctx.effectful() { + profiles::reload_system().await?; + } + } + tracker.idle(); + } + } + Ok(()) +} + +#[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.ssid = "Up\nstream".into(); + let err = connect(ctx.clone(), DeserializeStdin(req)) + .await + .unwrap_err(); + assert_eq!(err.kind, ErrorKind::InvalidValue); + + let err = connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstream\npass"))), + ) + .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 connect_and_disconnect_keep_a_zone_written_as_an_option() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + let firewall = read(dir.path(), "firewall").replace( + "\tlist network 'wan'\n\tlist network 'wan6'\n", + "\toption network 'wan wan6'\n", + ); + std::fs::write(dir.path().join("firewall"), &firewall).unwrap(); + async fn members(dir: &Path) -> Vec { + let arena = Arena::new(); + let cfgs = parse_all(dir.to_path_buf(), &arena, &["firewall"]) + .await + .unwrap(); + cfgs["firewall"].sections[0] + .get::() + .unwrap() + .network + } + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Open, None)), + ) + .await + .unwrap(); + assert_eq!(members(dir.path()).await, ["wan", "wan6", "wwan"]); + assert!(!read(dir.path(), "firewall").contains("option network")); + + disconnect(ctx).await.unwrap(); + assert_eq!(members(dir.path()).await, ["wan", "wan6"]); + } + + #[tokio::test] + async fn get_refuses_an_uplink_encryption_it_cannot_show() { + let dir = tempfile::tempdir().unwrap(); + let wireless = format!( + "{WIRELESS}\nconfig wifi-iface 'wwan'\n\toption device 'radio0'\n\toption mode 'sta'\n\toption network 'wwan'\n\toption ssid 'Upstream'\n\toption encryption 'wpa2'\n", + ); + let ctx = setup(dir.path(), &wireless, ""); + let err = get(ctx).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::CorruptedWifi); + } + + #[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()); + } + + const DDNS: &str = "config service 'wan'\n\toption enabled '1'\n\toption service_name 'duckdns.org'\n\toption ip_source 'network'\n\toption ip_network 'wan'\n\toption interface 'wan'\n\toption domain 'home.duckdns.org'\n"; + + #[tokio::test] + async fn ddns_publishes_the_active_uplink_while_an_uplink_exists() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + std::fs::write(dir.path().join("ddns"), DDNS).unwrap(); + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Open, None)), + ) + .await + .unwrap(); + let service = section(dir.path(), "ddns", "wan").unwrap(); + assert!(service.contains("option ip_source 'script'"), "{service}"); + assert!( + service.contains("option ip_script '/usr/bin/startwrt-cli wan uplink-ipv4'"), + "{service}" + ); + assert!(!service.contains("ip_network"), "{service}"); + assert!(service.contains("option interface 'wan'"), "{service}"); + assert!( + service.contains("option domain 'home.duckdns.org'"), + "{service}" + ); + + disconnect(ctx).await.unwrap(); + let service = section(dir.path(), "ddns", "wan").unwrap(); + assert!(service.contains("option ip_source 'network'"), "{service}"); + assert!(service.contains("option ip_network 'wan'"), "{service}"); + assert!(!service.contains("ip_script"), "{service}"); + } + + #[tokio::test] + async fn wan_port_created_beside_an_uplink_keeps_the_priority() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + let recreated = || async { + let arena = Arena::new(); + let mut cfgs = parse_all(dir.path().to_path_buf(), &arena, &["network"]) + .await + .unwrap(); + cfgs["network"] + .sections + .retain(|s| s.name().as_deref() != Some(WAN_INTERFACE)); + cfgs["network"] + .append(&UplinkInterface::default(), Some(WAN_INTERFACE)) + .unwrap(); + keep_wan_priority(&mut cfgs).unwrap(); + interface_metric(&cfgs, WAN_INTERFACE).unwrap() + }; + assert_eq!(recreated().await, None); + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Open, None)), + ) + .await + .unwrap(); + assert_eq!(recreated().await, Some(PREFERRED_METRIC)); + + priority_set( + ctx, + DeserializeStdin(WwanPrioritySetRequest { + priority: WwanPriority::Preferred, + }), + ) + .await + .unwrap(); + assert_eq!(recreated().await, Some(BACKUP_METRIC)); + } + + #[test] + fn uplink_on_a_served_address_range_is_a_conflict() { + let dump = |wwan: &str, mask: u8| { + serde_json::json!({ "interface": [ + { "interface": "loopback", "ipv4-address": [{ "address": "127.0.0.1", "mask": 8 }] }, + { "interface": "lan", "ipv4-address": [{ "address": "192.168.0.1", "mask": 24 }] }, + { "interface": "vlan_guest", "ipv4-address": [{ "address": "192.168.101.1", "mask": 24 }] }, + { "interface": "wan", "ipv4-address": [{ "address": "192.168.0.9", "mask": 24 }] }, + { "interface": "wwan", "ipv4-address": [{ "address": wwan, "mask": mask }] }, + ]}) + }; + assert!(subnet_conflict(&dump("192.168.0.57", 24))); + assert!(subnet_conflict(&dump("192.168.101.4", 24))); + assert!(subnet_conflict(&dump("192.168.3.4", 16))); + assert!(!subnet_conflict(&dump("192.168.1.57", 24))); + assert!(!subnet_conflict(&dump("10.0.0.7", 8))); + assert!(!subnet_conflict(&serde_json::json!({ "interface": [ + { "interface": "lan", "ipv4-address": [{ "address": "192.168.0.1", "mask": 24 }] }, + { "interface": "wan", "ipv4-address": [{ "address": "192.168.0.9", "mask": 24 }] }, + ]}))); + } + + #[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); + } + + async fn stop_with(dir: &Path, attempted: &Attempted, reason: WwanStopReason) -> bool { + update(&TestContext(dir.to_path_buf()), |cfgs| { + apply_stop(cfgs, attempted, reason) + }) + .await + .unwrap() + } + + fn attempted(key: &str) -> Attempted { + Attempted { + device: "radio0".into(), + ssid: "Upstream".into(), + encryption: "psk2".into(), + key: Some(key.into()), + } + } + + #[tokio::test] + async fn stopped_uplink_reports_why_and_frees_its_radio() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + assert_eq!( + get(ctx.clone()).await.unwrap().uplink.unwrap().stopped, + None + ); + + assert!( + stop_with( + dir.path(), + &attempted("upstreampass"), + WwanStopReason::Rejected + ) + .await + ); + assert!(section(dir.path(), "wireless", WWAN_INTERFACE) + .unwrap() + .contains("option disabled '1'")); + assert!(section(dir.path(), "startwrt", STOP_SECTION) + .unwrap() + .contains("option reason 'rejected'")); + let res = get(ctx).await.unwrap(); + assert_eq!(res.uplink.unwrap().stopped, Some(WwanStopReason::Rejected)); + let arena = Arena::new(); + let cfgs = parse_all(dir.path().to_path_buf(), &arena, &["wireless"]) + .await + .unwrap(); + assert!(uplink_radios(&cfgs).unwrap().is_empty()); + } + + #[tokio::test] + async fn uplink_turned_off_elsewhere_reads_as_disabled() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + let wireless = read(dir.path(), "wireless").replace( + "option key 'upstreampass'\n", + "option key 'upstreampass'\n\toption disabled '1'\n", + ); + std::fs::write(dir.path().join("wireless"), wireless).unwrap(); + assert_eq!( + get(ctx).await.unwrap().uplink.unwrap().stopped, + Some(WwanStopReason::Disabled) + ); + } + + #[tokio::test] + async fn stop_leaves_a_changed_or_stopped_uplink_alone() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("newpassword"))), + ) + .await + .unwrap(); + let before = read(dir.path(), "wireless"); + assert!( + !stop_with( + dir.path(), + &attempted("upstreampass"), + WwanStopReason::Rejected + ) + .await + ); + assert_eq!(read(dir.path(), "wireless"), before); + + assert!( + stop_with( + dir.path(), + &attempted("newpassword"), + WwanStopReason::Unreachable + ) + .await + ); + let stopped = read(dir.path(), "startwrt"); + assert!( + !stop_with( + dir.path(), + &attempted("newpassword"), + WwanStopReason::Rejected + ) + .await + ); + assert_eq!(read(dir.path(), "startwrt"), stopped); + } + + #[tokio::test] + async fn reconnect_clears_the_stop() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + stop_with( + dir.path(), + &attempted("upstreampass"), + WwanStopReason::Rejected, + ) + .await; + + assert_eq!( + reconnect(ctx.clone()).await.unwrap(), + WwanJoinOutcome::Joining + ); + assert!(!section(dir.path(), "wireless", WWAN_INTERFACE) + .unwrap() + .contains("option disabled '1'")); + assert!(section(dir.path(), "startwrt", STOP_SECTION).is_none()); + assert_eq!(get(ctx).await.unwrap().uplink.unwrap().stopped, None); + } + + #[tokio::test] + async fn reconnect_needs_an_uplink_on_a_radio_that_is_on() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + let err = reconnect(ctx.clone()).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::NotFound); + + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + stop_with( + dir.path(), + &attempted("upstreampass"), + WwanStopReason::Rejected, + ) + .await; + let wireless = read(dir.path(), "wireless").replacen( + "\toption channel 'auto'\n", + "\toption channel 'auto'\n\toption disabled '1'\n", + 1, + ); + std::fs::write(dir.path().join("wireless"), &wireless).unwrap(); + let err = reconnect(ctx).await.unwrap_err(); + assert_eq!(err.kind, ErrorKind::WifiRadioUnavailable); + assert_eq!(read(dir.path(), "wireless"), wireless); + } + + #[tokio::test] + async fn connect_and_disconnect_clear_the_stop() { + let dir = tempfile::tempdir().unwrap(); + let ctx = setup(dir.path(), WIRELESS, ""); + for leave in [true, false] { + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + stop_with( + dir.path(), + &attempted("upstreampass"), + WwanStopReason::Rejected, + ) + .await; + if leave { + disconnect(ctx.clone()).await.unwrap(); + } else { + connect( + ctx.clone(), + DeserializeStdin(connect_req(WwanSecurity::Wpa2, Some("upstreampass"))), + ) + .await + .unwrap(); + } + assert!(section(dir.path(), "startwrt", STOP_SECTION).is_none()); + } + } + + fn secs(n: u64) -> Duration { + Duration::from_secs(n) + } + + /// Seen \`ago\` before \`now\`. + fn sighting(ago: u64, level: i32) -> Sighting { + Sighting { + age: secs(ago), + level, + } + } + + /// A tracker past its first observation, and a time to count from. + fn started() -> (Tracker, Instant) { + let mut tracker = Tracker::default(); + tracker.idle(); + (tracker, Instant::now()) + } + + #[test] + fn join_that_never_connects_stops_as_unreachable() { + let (mut tracker, t0) = started(); + let uplink = attempted("upstreampass"); + assert_eq!( + tracker.observe(uplink.clone(), t0, false, &[]), + Verdict::Wait + ); + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(25), false, &[]), + Verdict::Wait + ); + assert_eq!( + tracker.observe(uplink, t0 + JOIN_TIMEOUT, false, &[]), + Verdict::Stop { + reason: WwanStopReason::Unreachable, + joining: true + } + ); + } + + #[test] + fn join_refused_in_range_stops_as_rejected() { + let (mut tracker, t0) = started(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, false, &[]); + tracker.observe(uplink.clone(), t0 + secs(15), false, &[sighting(2, -40)]); + assert_eq!( + tracker.observe(uplink, t0 + JOIN_TIMEOUT, false, &[sighting(17, -40)]), + Verdict::Stop { + reason: WwanStopReason::Rejected, + joining: true + } + ); + } + + #[test] + fn join_to_a_weak_network_stops_as_unreachable() { + let (mut tracker, t0) = started(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, false, &[]); + assert_eq!( + tracker.observe(uplink, t0 + JOIN_TIMEOUT, false, &[sighting(1, -82)]), + Verdict::Stop { + reason: WwanStopReason::Unreachable, + joining: true + } + ); + } + + #[test] + fn join_that_connects_is_reported_once() { + let (mut tracker, t0) = started(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, false, &[]); + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(10), true, &[]), + Verdict::Joined + ); + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(15), true, &[]), + Verdict::Wait + ); + // Dropping later is no longer a join. + assert_eq!( + tracker.observe(uplink, t0 + secs(15) + JOIN_TIMEOUT, false, &[]), + Verdict::Wait + ); + } + + #[test] + fn uplink_found_at_startup_is_not_a_join() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, false, &[]); + assert_eq!( + tracker.observe(uplink.clone(), t0 + JOIN_TIMEOUT, false, &[]), + Verdict::Wait + ); + assert_eq!( + tracker.observe(uplink, t0 + secs(600), false, &[]), + Verdict::Wait + ); + } + + #[test] + fn network_refusing_in_range_stops_after_two_minutes() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, true, &[]); + // Refused from here on: seen on every retry. + tracker.observe(uplink.clone(), t0 + secs(5), false, &[sighting(1, -50)]); + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(100), false, &[sighting(30, -50)]), + Verdict::Wait + ); + assert_eq!( + tracker.observe( + uplink, + t0 + secs(5) + REFUSED_TIMEOUT, + false, + &[sighting(60, -50)] + ), + Verdict::Stop { + reason: WwanStopReason::Rejected, + joining: false + } + ); + } + + #[test] + fn network_gone_since_the_drop_keeps_retrying() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, true, &[]); + // Last seen before the drop. + for t in [10, 60, 125, 400] { + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(t), false, &[sighting(t + 3, -40)]), + Verdict::Wait + ); + } + } + + #[test] + fn network_returning_after_an_outage_has_time_to_authenticate() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, true, &[]); + for t in [5, 60, 120, 300] { + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(t), false, &[]), + Verdict::Wait + ); + } + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(305), false, &[sighting(1, -50)]), + Verdict::Wait + ); + assert_eq!( + tracker.observe(uplink, t0 + secs(310), true, &[]), + Verdict::Wait + ); + } + + #[test] + fn losing_sight_of_the_network_resets_the_refusal_timeout() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, true, &[]); + tracker.observe(uplink.clone(), t0 + secs(5), false, &[sighting(1, -50)]); + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(100), false, &[]), + Verdict::Wait + ); + for t in [300, 360, 419] { + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(t), false, &[sighting(1, -50)]), + Verdict::Wait + ); + } + assert_eq!( + tracker.observe(uplink, t0 + secs(420), false, &[sighting(1, -50)]), + Verdict::Stop { + reason: WwanStopReason::Rejected, + joining: false + } + ); + } + + #[test] + fn network_last_seen_long_ago_keeps_retrying() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, true, &[]); + tracker.observe(uplink.clone(), t0 + secs(10), false, &[sighting(1, -40)]); + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(130), false, &[]), + Verdict::Wait + ); + assert_eq!( + tracker.observe(uplink, t0 + secs(300), false, &[]), + Verdict::Wait + ); + } + + #[test] + fn weak_network_keeps_retrying() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + let uplink = attempted("upstreampass"); + tracker.observe(uplink.clone(), t0, true, &[]); + for t in [10, 60, 125, 400] { + assert_eq!( + tracker.observe(uplink.clone(), t0 + secs(t), false, &[sighting(1, -80)]), + Verdict::Wait + ); + } + } + + #[test] + fn changed_uplink_is_a_new_join() { + let mut tracker = Tracker::default(); + let t0 = Instant::now(); + tracker.observe(attempted("upstreampass"), t0, true, &[]); + let changed = attempted("newpassword"); + tracker.observe(changed.clone(), t0 + secs(5), false, &[]); + assert_eq!( + tracker.observe(changed, t0 + secs(5) + JOIN_TIMEOUT, false, &[]), + Verdict::Stop { + reason: WwanStopReason::Unreachable, + joining: true + } + ); + } + + #[test] + fn ssid_text_matches_wpa_supplicant() { + assert_eq!(wpa_ssid_text("Home"), "Home"); + assert_eq!( + wpa_ssid_text("Café \"A\\B\"\t"), + "Caf\\xc3\\xa9 \\\"A\\\\B\\\"\\t" + ); + } + + #[test] + fn bss_pages_yield_sightings_of_the_network() { + let page = "id=3\nlevel=-48\nage=4\nssid=Upstream\n====\nid=5\nlevel=-70\nage=12\nssid=Neighbor\n====\nid=9\nlevel=-61\nage=0\nssid=Upstream\n####"; + let (seen, last, complete) = parse_bss_page(page, "Upstream"); + assert_eq!(seen, vec![sighting(4, -48), sighting(0, -61)]); + assert_eq!(last, Some(9)); + assert!(complete); + + let truncated = "id=3\nlevel=-48\nage=4\nssid=Caf\\xc3\\xa9\n====\n"; + let (seen, last, complete) = parse_bss_page(truncated, "Café"); + assert_eq!(seen, vec![sighting(4, -48)]); + assert_eq!(last, Some(3)); + assert!(!complete); + + assert_eq!(parse_bss_page("", "Upstream"), (Vec::new(), None, false)); + } +} diff --git a/projects/start-wrt/backend/hotplug/99-startwrt-ddns b/projects/start-wrt/backend/hotplug/99-startwrt-ddns new file mode 100755 index 0000000000..c71578457c --- /dev/null +++ b/projects/start-wrt/backend/hotplug/99-startwrt-ddns @@ -0,0 +1,5 @@ +#!/bin/sh +# Runs after ddns-scripts' 95-ddns hook, which stops the updater when wan goes down. +[ "$ACTION" = "ifup" -o "$ACTION" = "ifupdate" -o "$ACTION" = "ifdown" ] && [ "$INTERFACE" = "wan" -o "$INTERFACE" = "wwan" ] && [ "$(uci -q get ddns.wan.ip_source)" = "script" ] && [ "$(uci -q get ddns.wan.enabled)" = "1" ] && { + (/etc/init.d/ddns stop wan; /etc/init.d/ddns start wan) 2>/dev/null & +} 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/backend/uciedit/src/openwrt.rs b/projects/start-wrt/backend/uciedit/src/openwrt.rs index 0c5d095664..6a05f8c43e 100644 --- a/projects/start-wrt/backend/uciedit/src/openwrt.rs +++ b/projects/start-wrt/backend/uciedit/src/openwrt.rs @@ -652,6 +652,9 @@ pub struct DdnsService { pub ip_source: Option, #[uci(default)] pub ip_network: Option, + /// Command whose output is the address to publish, for `ip_source 'script'`. + #[uci(default)] + pub ip_script: Option, /// Binds the section to hotplug ifup/ifdown events for this interface #[uci(default)] pub interface: Option, diff --git a/projects/start-wrt/build/stage-files.sh b/projects/start-wrt/build/stage-files.sh index 1053609ef4..cb1a4a15d2 100755 --- a/projects/start-wrt/build/stage-files.sh +++ b/projects/start-wrt/build/stage-files.sh @@ -162,6 +162,8 @@ cp "$PROJECT_DIR"/backend/hotplug/99-startwrt-published-ports "${FILES_DIR}/etc/ chmod +x "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-published-ports" cp "$PROJECT_DIR"/backend/hotplug/99-startwrt-port-control "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-port-control" chmod +x "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-port-control" +cp "$PROJECT_DIR"/backend/hotplug/99-startwrt-ddns "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-ddns" +chmod +x "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-ddns" cp "$PROJECT_DIR"/backend/hotplug/99-startwrt-smartdns "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-smartdns" chmod +x "${FILES_DIR}/etc/hotplug.d/iface/99-startwrt-smartdns" 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..9e884b6904 --- /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 im neuen Tab „Drahtloses WAN“ unter `Internet > WAN-Einstellungen` 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..8b7b81beca --- /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 pestaña WAN inalámbrica de `Internet > Configuración de WAN`. 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..e0a26258cb --- /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 dans le nouvel onglet WAN sans fil de `Internet > Paramètres WAN`. 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..4763712da5 --- /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 Wireless WAN tab under `Internet > WAN Settings`. 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..778a58d9c4 --- /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 w nowej karcie Bezprzewodowy WAN w `Internet > Ustawienia 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/wan.md b/projects/start-wrt/docs/src/wan.md index 4e64013897..ea28cfb541 100644 --- a/projects/start-wrt/docs/src/wan.md +++ b/projects/start-wrt/docs/src/wan.md @@ -67,3 +67,7 @@ Some ISPs bind your Internet connection to a specific MAC address. If you are re ## Dynamic DNS See [Dynamic DNS](ddns.md) for full details on configuring DDNS from this tab. + +## Wireless WAN + +See [Wireless WAN](wireless-wan.md) for connecting the router to another Wi-Fi network from this tab. 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 f341cd6acc..38d12e782e 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 while the router is trying to join that network. - **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..6ce28da6d5 --- /dev/null +++ b/projects/start-wrt/docs/src/wireless-wan.md @@ -0,0 +1,55 @@ +# 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 > WAN Settings > 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] +> Devices on the network the router joins can reach the router's interface and SSH unless [Remote Access](settings.md#remote-access) is set to **Never**. The router offers to change it when you join. + +If the network uses the same address range as one of your own networks, such as `192.168.0.x`, the router connects but your devices cannot reach the Internet through it. The **Summary** says so. Change the range under [LAN Settings](lan.md) or on the [security profile](security-profiles.md), or use a different upstream network. + +> [!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, and while 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. + +## When the router cannot connect + +The router gives up on a network it cannot join, so that its own Wi-Fi on that band comes back on: + +- **Joining** — If the router has not connected within 30 seconds of **Join**, it stops trying. The page says whether the network refused it, usually because of a wrong password, or could not be found. +- **Later** — If a network in range keeps refusing the router for two minutes, for example after its password changed, the router stops trying. + +The **Summary** then shows **Stopped** with the reason. Click **Retry** to try the same settings again, or **Change password** to enter a new one. Once the uplink has connected, a network that goes out of range or has a weak signal is not given up on: the router keeps trying, and reconnects when the network is back. + +## 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 router is trying to join the network. Its channel setting has no effect until the uplink is removed or stopped. +- **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 address of whichever connection is carrying traffic. +- **Inbound connections** — While both connections are up, published ports, remote access and inbound VPNs are reachable at the address of the one in use. diff --git a/projects/start-wrt/web/src/app/app.icons.ts b/projects/start-wrt/web/src/app/app.icons.ts index 25cb1eb7a1..378b018078 100644 --- a/projects/start-wrt/web/src/app/app.icons.ts +++ b/projects/start-wrt/web/src/app/app.icons.ts @@ -59,6 +59,9 @@ import shield from '@taiga-ui/icons/src/shield.svg' import terminal from '@taiga-ui/icons/src/terminal.svg' import trash from '@taiga-ui/icons/src/trash.svg' import userLock from '@taiga-ui/icons/src/user-lock.svg' +import wifiHigh from '@taiga-ui/icons/src/wifi-high.svg' +import wifiLow from '@taiga-ui/icons/src/wifi-low.svg' +import wifiOff from '@taiga-ui/icons/src/wifi-off.svg' import wifi from '@taiga-ui/icons/src/wifi.svg' import x from '@taiga-ui/icons/src/x.svg' @@ -125,5 +128,8 @@ export const ICONS = { '@tui.trash': trash, '@tui.user-lock': userLock, '@tui.wifi': wifi, + '@tui.wifi-high': wifiHigh, + '@tui.wifi-low': wifiLow, + '@tui.wifi-off': wifiOff, '@tui.x': x, } diff --git a/projects/start-wrt/web/src/app/components/custom-config.ts b/projects/start-wrt/web/src/app/components/custom-config.ts index 8f87436a5a..76045a5e52 100644 --- a/projects/start-wrt/web/src/app/components/custom-config.ts +++ b/projects/start-wrt/web/src/app/components/custom-config.ts @@ -20,6 +20,8 @@ const PROBLEMS: Record = { 'StartWRT shows one of these per radio. This one was added outside StartWRT.', unmanaged: 'This section also has {option} {value}, set outside StartWRT. StartWRT shows the first value and leaves this one as it is.', + uplink: + 'This Wi-Fi uplink was set up outside StartWRT. Wi-Fi on its band follows the upstream network’s channel and is off while the uplink is disconnected. To turn that band off, remove the uplink in LuCI first.', } function key(finding: ConfigFinding): string { 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 1aa9508b41..4fb5f0f9c7 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,26 @@ 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.`, + '/wan/wireless-wan': `## WAN – 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. + +Solange der Fernzugriff eingeschaltet ist, können Geräte im Netzwerk, dem der Router beitritt, seine Weboberfläche und SSH erreichen. Beim Beitreten können Sie den Fernzugriff zuerst ausschalten. + +### 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. Treten Sie von einem kabelgebundenen Gerät oder, bei einem Router mit zwei Frequenzbändern, über das andere Frequenzband bei. Kann der Router einem gerade eingetragenen Netzwerk nicht beitreten oder weist ihn ein Netzwerk in Reichweite zwei Minuten lang ab, versucht er es nicht mehr, und das WLAN dieses Frequenzbands schaltet sich wieder ein; mit **Wiederholen** oder **Passwort ändern** geht es weiter, wobei sich das WLAN dieses Frequenzbands wieder ausschaltet, bis der Router verbunden ist. 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 3be2cdb6f1..c70e7511de 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,26 @@ 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.`, + '/wan/wireless-wan': `## WAN – 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. + +While Remote Access is on, devices on the network the router joins can reach its web interface and SSH. Joining offers to turn Remote Access off first. + +### 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. Join from a wired device or, on a router with two bands, from the other band. If the router cannot join a network it was just given, or a network in range refuses it for two minutes, it stops trying and that band's Wi-Fi comes back on; select **Retry** or **Change password** to resume, which turns that band's Wi-Fi off again until the router connects. 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 7033d6c155..8ade7be980 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,26 @@ 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.`, + '/wan/wireless-wan': `## WAN – 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. + +Mientras el acceso remoto esté activado, los dispositivos de la red a la que se une el router pueden acceder a su interfaz web y a SSH. Al unirse, se le ofrece desactivar antes el acceso remoto. + +### 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. Únase desde un dispositivo con cable o, en un router con dos bandas, desde la otra banda. Si el router no puede unirse a una red que acaba de recibir, o una red al alcance lo rechaza durante dos minutos, deja de intentarlo y la Wi-Fi de esa banda vuelve a encenderse; pulse **Reintentar** o **Cambiar contraseña** para reanudar, lo que vuelve a apagar la Wi-Fi de esa banda hasta que el router se conecte. 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 4f155f4531..c44d1ec221 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,26 @@ 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.`, + '/wan/wireless-wan': `## WAN – 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. + +Tant que l’accès à distance est activé, les appareils du réseau que rejoint le routeur peuvent atteindre son interface web et SSH. Au moment de rejoindre un réseau, vous pouvez d’abord désactiver l’accès à distance. + +### 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. Rejoignez-le depuis un appareil filaire ou, sur un routeur à deux bandes, depuis l’autre bande. Si le routeur ne parvient pas à rejoindre un réseau qui vient de lui être indiqué, ou si un réseau à portée le refuse pendant deux minutes, il cesse d’essayer et le Wi-Fi de cette bande se rallume ; choisissez **Réessayer** ou **Changer le mot de passe** pour reprendre, ce qui éteint de nouveau le Wi-Fi de cette bande jusqu’à ce que le routeur soit connecté. 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 43435a5eea..d912053796 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,26 @@ 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.`, + '/wan/wireless-wan': `## WAN – 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. + +Dopóki dostęp zdalny jest włączony, urządzenia w sieci, do której dołącza router, mogą łączyć się z jego interfejsem WWW i SSH. Podczas dołączania możesz najpierw wyłączyć dostęp zdalny. + +### 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ą. Dołącz z urządzenia przewodowego lub, jeśli router ma dwa pasma, z drugiego pasma. Jeśli router nie może dołączyć do właśnie podanej sieci albo sieć w zasięgu odrzuca go przez dwie minuty, przestaje próbować, a Wi-Fi tego pasma włącza się ponownie; wybierz **Ponów** lub **Zmień hasło**, aby wznowić, co ponownie wyłącza Wi-Fi tego pasma do czasu połączenia routera. 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 3324b3fdea..f841366176 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts @@ -594,4 +594,59 @@ export default { 630: 'Zeile {line}', 631: 'Erneut prüfen', 632: 'Dieser Abschnitt hat außerdem {option} {value}, gesetzt außerhalb von StartWRT. StartWRT zeigt den ersten Wert an und lässt diesen unverändert.', + 633: 'Drahtloses WAN', + 634: 'Verbinden Sie den Router mit einem anderen WLAN, um auf das Internet zuzugreifen, als Reserve für den WAN-Anschluss oder an seiner Stelle.', + 635: 'In LuCI wurde ein WLAN-Uplink eingerichtet. Verwalten Sie ihn dort, oder löschen Sie ihn dort, um den Uplink hier zu verwalten.', + 636: 'Netzwerkname', + 637: 'Signal', + 638: 'Frequenzband', + 639: 'Priorität', + 640: 'Solange der Router nicht mit diesem Netzwerk verbunden ist, ist sein eigenes WLAN in diesem Frequenzband aus.', + 641: 'Uplink entfernen', + 642: 'Verfügbare Netzwerke', + 643: 'Verborgenes Netzwerk', + 644: 'Suchen', + 645: 'Suchen Sie, um die WLANs aufzulisten, die dieses Frequenzband erreicht.', + 646: 'Schalten Sie das WLAN ein, um einem Netzwerk beizutreten.', + 647: 'Verbindung wird hergestellt', + 648: 'In Verwendung', + 649: 'In Bereitschaft', + 650: 'Suche läuft', + 651: 'Uplink entfernen?', + 652: 'Der Router verlässt dieses Netzwerk. Sein Internetzugang hängt dann allein vom WAN-Anschluss ab.', + 653: 'Netzwerk wird beigetreten', + 655: 'Uplink wird entfernt', + 656: 'Uplink entfernt', + 657: 'Netzwerk beitreten', + 658: 'Beitreten', + 662: 'Reserve: wird verwendet, solange der WAN-Anschluss keine Verbindung hat', + 663: 'Bevorzugt: wird verwendet, solange verbunden; der WAN-Anschluss übernimmt, wenn die Verbindung abbricht', + 664: 'Kanal', + 665: 'Nicht unterstützt', + 666: 'Keine Netzwerke gefunden', + 667: '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.', + 668: 'Dieser WLAN-Uplink wurde außerhalb von StartWRT eingerichtet. Das WLAN auf seinem Frequenzband folgt dem Kanal des vorgelagerten Netzwerks und ist aus, solange der Uplink getrennt ist. Um dieses Frequenzband auszuschalten, entfernen Sie zuerst den Uplink in LuCI.', + 669: 'Gestoppt', + 670: 'Passwort ändern', + 671: 'Netzwerk beigetreten', + 672: '{ssid} hat den Router nicht angenommen, daher versucht der Router nicht mehr, dem Netzwerk beizutreten. Prüfen Sie das Passwort.', + 673: 'Der Router hat {ssid} nicht gefunden und versucht nicht mehr, dem Netzwerk beizutreten. Prüfen Sie, ob das Netzwerk eingeschaltet und in Reichweite ist.', + 674: 'Der Uplink zu {ssid} ist ausgeschaltet.', + 675: 'Der Router versucht weiter, sich zu verbinden. Bis dahin ist sein eigenes WLAN in diesem Frequenzband aus.', + 676: 'Der Fernzugriff ist eingeschaltet', + 677: 'Geräte im Netzwerk, dem der Router beitritt, können seine Weboberfläche und SSH erreichen, solange der Fernzugriff eingeschaltet ist.', + 678: 'Fernzugriff ausschalten und beitreten', + 679: 'Trotzdem beitreten', + 680: 'Zu lang', + 681: 'Muss mindestens 8 Zeichen lang sein', + 682: 'Darf keine Steuerzeichen enthalten', + 683: 'Dieses Frequenzband trägt den WLAN-Uplink. Entfernen Sie den Uplink unter WAN › Drahtloses WAN, bevor Sie das Frequenzband ausschalten.', + 684: 'Das WLAN in diesem Frequenzband ist aus. Schalten Sie es ein, um einem Netzwerk beizutreten.', + 685: 'Der Router versucht weiter, dem Netzwerk beizutreten. Die Übersicht zeigt das Ergebnis.', + 686: 'Der Router konnte dem Netzwerk nicht beitreten.', + 687: 'Ein erneuter Versuch schaltet das eigene WLAN des Routers in diesem Frequenzband wieder aus, bis er verbunden ist.', + 688: 'Treten Sie von einem kabelgebundenen Gerät oder über das andere Frequenzband bei.', + 689: 'Treten Sie von einem kabelgebundenen Gerät bei.', + 690: 'Offen (kein Passwort)', + 691: 'Dieses Netzwerk verwendet denselben Adressbereich wie eines Ihrer eigenen Netzwerke, sodass Ihre Geräte darüber das Internet nicht erreichen. Ändern Sie Ihren Bereich unter LAN-Einstellungen oder Sicherheitsprofile.', } 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 aa19164d8b..efb460c311 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts @@ -599,4 +599,59 @@ export const ENGLISH: Record = { 'line {line}': 630, 'Check again': 631, 'This section also has {option} {value}, set outside StartWRT. StartWRT shows the first value and leaves this one as it is.': 632, + 'Wireless WAN': 633, + 'Connect the router to another Wi-Fi network for Internet access, as a backup to the WAN port or in its place.': 634, + 'A Wi-Fi uplink was set up in LuCI. Manage it there, or delete it there to manage the uplink here.': 635, + 'Network name': 636, + 'Signal': 637, + 'Band': 638, + 'Priority': 639, + 'While the router is not connected to this network, its own Wi-Fi on this band is off.': 640, + 'Remove uplink': 641, + 'Available networks': 642, + 'Hidden network': 643, + 'Scan': 644, + 'Scan to list the Wi-Fi networks this band can reach.': 645, + 'Turn on Wi-Fi to join a network.': 646, + 'Connecting': 647, + 'In use': 648, + 'Standing by': 649, + 'Scanning': 650, + 'Remove uplink?': 651, + 'The router will leave this network. Its Internet access then depends on the WAN port alone.': 652, + 'Joining network': 653, + 'Removing uplink': 655, + 'Uplink removed': 656, + 'Join network': 657, + 'Join': 658, + 'Backup: used while the WAN port has no connection': 662, + 'Preferred: used while connected, with the WAN port taking over when it drops': 663, + 'Channel': 664, + 'Unsupported': 665, + 'No networks found': 666, + '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.': 667, + 'This Wi-Fi uplink was set up outside StartWRT. Wi-Fi on its band follows the upstream network’s channel and is off while the uplink is disconnected. To turn that band off, remove the uplink in LuCI first.': 668, + 'Stopped': 669, + 'Change password': 670, + 'Joined network': 671, + '{ssid} didn’t accept the router, so the router stopped trying to join it. Check the password.': 672, + 'The router couldn’t find {ssid}, so it stopped trying to join it. Check that the network is on and in range.': 673, + 'The uplink to {ssid} is turned off.': 674, + 'The router keeps trying to connect. Until it does, its own Wi-Fi on this band is off.': 675, + 'Remote Access is on': 676, + 'Devices on the network the router joins can reach its web interface and SSH while Remote Access is on.': 677, + 'Turn off Remote Access and join': 678, + 'Join anyway': 679, + 'Too long': 680, + 'Must be at least 8 characters': 681, + 'Must not contain control characters': 682, + 'This band carries the Wi-Fi uplink. Remove the uplink under WAN › Wireless WAN before turning the band off.': 683, + 'Wi-Fi on this band is off. Turn it on to join a network.': 684, + 'The router is still trying to join the network. The Summary shows the result.': 685, + 'The router couldn’t join the network.': 686, + 'Retrying turns the router’s own Wi-Fi on this band off again until it connects.': 687, + 'Join from a wired device or from the other band.': 688, + 'Join from a wired device.': 689, + 'Open (no password)': 690, + 'This network uses the same address range as one of your own networks, so your devices cannot reach the Internet through it. Change your range under LAN Settings or Security Profiles.': 691, } 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 3d858e55b8..ac53c3ad3c 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts @@ -594,4 +594,59 @@ export default { 630: 'línea {line}', 631: 'Comprobar de nuevo', 632: 'Esta sección también tiene {option} {value}, establecido fuera de StartWRT. StartWRT muestra el primer valor y deja este tal como está.', + 633: 'WAN inalámbrica', + 634: 'Conecte el router a otra red Wi-Fi para acceder a Internet, como respaldo del puerto WAN o en su lugar.', + 635: 'Se configuró un enlace Wi-Fi en LuCI. Adminístrelo allí, o elimínelo allí para administrar el enlace aquí.', + 636: 'Nombre de la red', + 637: 'Señal', + 638: 'Banda', + 639: 'Prioridad', + 640: 'Mientras el router no esté conectado a esta red, su propia Wi-Fi en esta banda está apagada.', + 641: 'Quitar enlace', + 642: 'Redes disponibles', + 643: 'Red oculta', + 644: 'Buscar', + 645: 'Busque para ver las redes Wi-Fi que alcanza esta banda.', + 646: 'Active la Wi-Fi para unirse a una red.', + 647: 'Conectando', + 648: 'En uso', + 649: 'En espera', + 650: 'Buscando', + 651: '¿Quitar enlace?', + 652: 'El router dejará esta red. Su acceso a Internet dependerá entonces solo del puerto WAN.', + 653: 'Uniéndose a la red', + 655: 'Quitando enlace', + 656: 'Enlace quitado', + 657: 'Unirse a la red', + 658: 'Unirse', + 662: 'Respaldo: se usa mientras el puerto WAN no tiene conexión', + 663: 'Preferida: se usa mientras está conectada; el puerto WAN toma el relevo cuando se cae', + 664: 'Canal', + 665: 'No compatible', + 666: 'No se encontraron redes', + 667: '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.', + 668: 'Este enlace Wi-Fi se configuró fuera de StartWRT. La Wi-Fi de su banda sigue el canal de la red de origen y está apagada mientras el enlace está desconectado. Para apagar esa banda, quite primero el enlace en LuCI.', + 669: 'Detenido', + 670: 'Cambiar contraseña', + 671: 'Unido a la red', + 672: '{ssid} no aceptó el router, así que el router dejó de intentar unirse. Revise la contraseña.', + 673: 'El router no encontró {ssid}, así que dejó de intentar unirse. Compruebe que la red esté encendida y al alcance.', + 674: 'El enlace a {ssid} está apagado.', + 675: 'El router sigue intentando conectarse. Hasta que lo logre, su propia Wi-Fi en esta banda está apagada.', + 676: 'El acceso remoto está activado', + 677: 'Los dispositivos de la red a la que se une el router pueden acceder a su interfaz web y a SSH mientras el acceso remoto esté activado.', + 678: 'Desactivar el acceso remoto y unirse', + 679: 'Unirse de todos modos', + 680: 'Demasiado largo', + 681: 'Debe tener al menos 8 caracteres', + 682: 'No debe contener caracteres de control', + 683: 'Esta banda lleva el enlace Wi-Fi. Quite el enlace en WAN › WAN inalámbrica antes de apagar la banda.', + 684: 'La Wi-Fi de esta banda está apagada. Enciéndala para unirse a una red.', + 685: 'El router sigue intentando unirse a la red. La sección Resumen muestra el resultado.', + 686: 'El router no pudo unirse a la red.', + 687: 'Al reintentar, la Wi-Fi propia del router en esta banda vuelve a apagarse hasta que se conecte.', + 688: 'Únase desde un dispositivo con cable o desde la otra banda.', + 689: 'Únase desde un dispositivo con cable.', + 690: 'Abierta (sin contraseña)', + 691: 'Esta red usa el mismo rango de direcciones que una de sus propias redes, por lo que sus dispositivos no pueden acceder a Internet a través de ella. Cambie su rango en Configuración de LAN o Perfiles de seguridad.', } 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 a3b31710bc..c389dc594b 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts @@ -594,4 +594,59 @@ export default { 630: 'ligne {line}', 631: 'Vérifier à nouveau', 632: 'Cette section contient aussi {option} {value}, défini en dehors de StartWRT. StartWRT affiche la première valeur et laisse celle-ci telle quelle.', + 633: 'WAN sans fil', + 634: 'Connectez le routeur à un autre réseau Wi-Fi pour accéder à Internet, en secours du port WAN ou à sa place.', + 635: '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.', + 636: 'Nom du réseau', + 637: 'Signal', + 638: 'Bande', + 639: 'Priorité', + 640: 'Tant que le routeur n’est pas connecté à ce réseau, son propre Wi-Fi sur cette bande est éteint.', + 641: 'Supprimer la liaison', + 642: 'Réseaux disponibles', + 643: 'Réseau masqué', + 644: 'Rechercher', + 645: 'Lancez une recherche pour lister les réseaux Wi-Fi que cette bande atteint.', + 646: 'Activez le Wi-Fi pour rejoindre un réseau.', + 647: 'Connexion en cours', + 648: 'Utilisé', + 649: 'En attente', + 650: 'Recherche en cours', + 651: 'Supprimer la liaison ?', + 652: 'Le routeur quittera ce réseau. Son accès à Internet dépendra alors du seul port WAN.', + 653: 'Connexion au réseau', + 655: 'Suppression de la liaison', + 656: 'Liaison supprimée', + 657: 'Rejoindre le réseau', + 658: 'Rejoindre', + 662: 'Secours : utilisé tant que le port WAN n’a pas de connexion', + 663: 'Préféré : utilisé tant qu’il est connecté, le port WAN prenant le relais en cas de coupure', + 664: 'Canal', + 665: 'Non pris en charge', + 666: 'Aucun réseau trouvé', + 667: '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.', + 668: 'Cette liaison montante Wi-Fi a été configurée en dehors de StartWRT. Le Wi-Fi de sa bande suit le canal du réseau amont et est éteint tant que la liaison est déconnectée. Pour éteindre cette bande, supprimez d’abord la liaison dans LuCI.', + 669: 'Arrêtée', + 670: 'Changer le mot de passe', + 671: 'Réseau rejoint', + 672: '{ssid} n’a pas accepté le routeur, qui a donc cessé d’essayer de le rejoindre. Vérifiez le mot de passe.', + 673: 'Le routeur n’a pas trouvé {ssid} et a cessé d’essayer de le rejoindre. Vérifiez que le réseau est allumé et à portée.', + 674: 'La liaison vers {ssid} est désactivée.', + 675: 'Le routeur continue d’essayer de se connecter. D’ici là, son propre Wi-Fi sur cette bande est éteint.', + 676: 'L’accès à distance est activé', + 677: 'Les appareils du réseau que rejoint le routeur peuvent atteindre son interface web et SSH tant que l’accès à distance est activé.', + 678: 'Désactiver et rejoindre', + 679: 'Rejoindre quand même', + 680: 'Trop long', + 681: 'Doit comporter au moins 8 caractères', + 682: 'Ne doit pas contenir de caractères de contrôle', + 683: 'Cette bande porte la liaison montante Wi-Fi. Supprimez la liaison sous WAN › WAN sans fil avant d’éteindre la bande.', + 684: 'Le Wi-Fi de cette bande est éteint. Activez-le pour rejoindre un réseau.', + 685: 'Le routeur essaie toujours de rejoindre le réseau. La section Résumé affiche le résultat.', + 686: 'Le routeur n’a pas pu rejoindre le réseau.', + 687: 'Réessayer éteint de nouveau le Wi-Fi du routeur sur cette bande jusqu’à ce qu’il soit connecté.', + 688: 'Rejoignez-le depuis un appareil filaire ou depuis l’autre bande.', + 689: 'Rejoignez-le depuis un appareil filaire.', + 690: 'Ouvert (sans mot de passe)', + 691: 'Ce réseau utilise la même plage d’adresses que l’un de vos propres réseaux ; vos appareils ne peuvent donc pas accéder à Internet par son intermédiaire. Modifiez votre plage dans Paramètres LAN ou Profils de sécurité.', } 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 f235ef043c..7e9f739b09 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts @@ -594,4 +594,59 @@ export default { 630: 'wiersz {line}', 631: 'Sprawdź ponownie', 632: 'Ta sekcja ma także {option} {value}, ustawione poza StartWRT. StartWRT wyświetla pierwszą wartość, a tę pozostawia bez zmian.', + 633: 'Bezprzewodowy WAN', + 634: 'Połącz router z inną siecią Wi-Fi, aby uzyskać dostęp do Internetu, jako zapas dla portu WAN lub zamiast niego.', + 635: 'Łącze Wi-Fi zostało skonfigurowane w LuCI. Zarządzaj nim tam albo usuń je tam, aby zarządzać łączem tutaj.', + 636: 'Nazwa sieci', + 637: 'Sygnał', + 638: 'Pasmo', + 639: 'Priorytet', + 640: 'Dopóki router nie jest połączony z tą siecią, jego własne Wi-Fi w tym paśmie jest wyłączone.', + 641: 'Usuń łącze', + 642: 'Dostępne sieci', + 643: 'Ukryta sieć', + 644: 'Skanuj', + 645: 'Skanuj, aby wyświetlić sieci Wi-Fi dostępne w tym paśmie.', + 646: 'Włącz Wi-Fi, aby dołączyć do sieci.', + 647: 'Łączenie', + 648: 'W użyciu', + 649: 'W gotowości', + 650: 'Skanowanie', + 651: 'Usunąć łącze?', + 652: 'Router opuści tę sieć. Jego dostęp do Internetu będzie wtedy zależał wyłącznie od portu WAN.', + 653: 'Dołączanie do sieci', + 655: 'Usuwanie łącza', + 656: 'Łącze usunięte', + 657: 'Dołącz do sieci', + 658: 'Dołącz', + 662: 'Zapasowe: używane, gdy port WAN nie ma połączenia', + 663: 'Preferowane: używane, gdy jest połączenie; port WAN przejmuje, gdy ono zaniknie', + 664: 'Kanał', + 665: 'Nieobsługiwane', + 666: 'Nie znaleziono sieci', + 667: '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.', + 668: 'To łącze Wi-Fi skonfigurowano poza StartWRT. Wi-Fi w jego paśmie korzysta z kanału sieci nadrzędnej i jest wyłączone, gdy łącze jest rozłączone. Aby wyłączyć to pasmo, najpierw usuń łącze w LuCI.', + 669: 'Zatrzymane', + 670: 'Zmień hasło', + 671: 'Dołączono do sieci', + 672: 'Sieć {ssid} nie przyjęła routera, więc router przestał próbować do niej dołączyć. Sprawdź hasło.', + 673: 'Router nie znalazł sieci {ssid}, więc przestał próbować do niej dołączyć. Sprawdź, czy sieć jest włączona i w zasięgu.', + 674: 'Łącze do {ssid} jest wyłączone.', + 675: 'Router nadal próbuje się połączyć. Do tego czasu jego własne Wi-Fi w tym paśmie jest wyłączone.', + 676: 'Dostęp zdalny jest włączony', + 677: 'Urządzenia w sieci, do której dołącza router, mogą łączyć się z jego interfejsem WWW i SSH, dopóki dostęp zdalny jest włączony.', + 678: 'Wyłącz dostęp zdalny i dołącz', + 679: 'Dołącz mimo to', + 680: 'Za długie', + 681: 'Musi mieć co najmniej 8 znaków', + 682: 'Nie może zawierać znaków sterujących', + 683: 'To pasmo obsługuje łącze Wi-Fi. Usuń łącze w sekcji WAN › Bezprzewodowy WAN, zanim wyłączysz to pasmo.', + 684: 'Wi-Fi w tym paśmie jest wyłączone. Włącz je, aby dołączyć do sieci.', + 685: 'Router nadal próbuje dołączyć do sieci. Wynik pojawi się w sekcji Podsumowanie.', + 686: 'Router nie mógł dołączyć do sieci.', + 687: 'Ponowienie znów wyłącza własne Wi-Fi routera w tym paśmie do czasu połączenia.', + 688: 'Dołącz z urządzenia przewodowego lub z drugiego pasma.', + 689: 'Dołącz z urządzenia przewodowego.', + 690: 'Otwarta (bez hasła)', + 691: 'Ta sieć używa tego samego zakresu adresów co jedna z Twoich sieci, więc Twoje urządzenia nie mogą przez nią łączyć się z Internetem. Zmień swój zakres w Ustawieniach LAN lub Profilach bezpieczeństwa.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/routes/inbound/routes/table/index.ts b/projects/start-wrt/web/src/app/routes/inbound/routes/table/index.ts index f7763f93a6..f4c2c5a0a3 100644 --- a/projects/start-wrt/web/src/app/routes/inbound/routes/table/index.ts +++ b/projects/start-wrt/web/src/app/routes/inbound/routes/table/index.ts @@ -213,13 +213,13 @@ export default class InboundTable { const endpoints: VpnServerEndpoint[] = [] const [ipv4, ipv6, ddns] = await Promise.all([ - this.api.wanIpv4Get(), + this.api.wanUplinkIpv4(), this.api.wanIpv6Get(), this.api.wanDdnsGet(), ]) - if (ipv4.assigned_ip) { - endpoints.push({ address: ipv4.assigned_ip, label: 'WAN IPv4' }) + if (ipv4) { + endpoints.push({ address: ipv4, label: 'WAN IPv4' }) } if (ipv6.mode !== 'disabled' && ipv6.assigned_ipv6) { endpoints.push({ address: ipv6.assigned_ipv6, label: 'WAN IPv6' }) diff --git a/projects/start-wrt/web/src/app/routes/published-ports/index.ts b/projects/start-wrt/web/src/app/routes/published-ports/index.ts index 4dc3dc31ef..0bfbec62a5 100644 --- a/projects/start-wrt/web/src/app/routes/published-ports/index.ts +++ b/projects/start-wrt/web/src/app/routes/published-ports/index.ts @@ -96,11 +96,11 @@ export default class PublishedPorts { // Each call degrades independently: one failing WAN/LAN endpoint must not // reject the whole batch and leave ipv4EndpointHost/ipv6Available unset // (which suppressed every IPv4 endpoint in the table). - const [wanIpv6, lanIpv6, ddns, wanIpv4] = await Promise.all([ + const [wanIpv6, lanIpv6, ddns, uplinkIpv4] = await Promise.all([ this.api.wanIpv6Get().catch(() => null), this.api.lanIpv6Get().catch(() => null), this.api.wanDdnsGet().catch(() => null), - this.api.wanIpv4Get().catch(() => null), + this.api.wanUplinkIpv4().catch(() => null), ]) this.loadVpnProfiles() @@ -114,7 +114,7 @@ export default class PublishedPorts { // Use DDNS hostname if available, otherwise WAN IP const ddnsHostname = ddns?.enabled ? ddns.hostname || null : null - this.ipv4EndpointHost.set(ddnsHostname || wanIpv4?.assigned_ip || null) + this.ipv4EndpointHost.set(ddnsHostname || uplinkIpv4 || null) } private async loadVpnProfiles() { diff --git a/projects/start-wrt/web/src/app/routes/wan/index.ts b/projects/start-wrt/web/src/app/routes/wan/index.ts index 14b156e60e..b17bff5593 100644 --- a/projects/start-wrt/web/src/app/routes/wan/index.ts +++ b/projects/start-wrt/web/src/app/routes/wan/index.ts @@ -45,6 +45,7 @@ class Wan { 'DNS', 'MAC Address', 'Dynamic DNS', + 'Wireless WAN', ] } @@ -73,6 +74,10 @@ export default [ path: 'dynamic-dns', loadComponent: () => import('./routes/ddns'), }, + { + path: 'wireless-wan', + loadComponent: () => import('./routes/wireless-wan'), + }, { path: '**', redirectTo: 'ipv4', diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/dialog.ts b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/dialog.ts new file mode 100644 index 0000000000..3a190c6e69 --- /dev/null +++ b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/dialog.ts @@ -0,0 +1,222 @@ +import { Component, inject, signal } from '@angular/core' +import { + NonNullableFormBuilder, + ReactiveFormsModule, + Validators, +} from '@angular/forms' +import { WA_IS_MOBILE } from '@ng-web-apis/platform' +import { + tuiMarkControlAsTouchedAndValidate, + TuiAutoFocus, + TuiValueChanges, +} from '@taiga-ui/cdk' +import { + TuiButton, + TuiDataList, + TuiDialogContext, + TuiError, + TuiIcon, + TuiInput, + TuiNotification, + TuiTextfield, + tuiTextfieldOptionsProvider, + TuiTitle, +} from '@taiga-ui/core' +import type { TuiContext } from '@taiga-ui/cdk' +import { TuiChevron, TuiPassword, TuiRadioList, TuiSelect } from '@taiga-ui/kit' +import { TuiForm, TuiHeader } from '@taiga-ui/layout' +import { injectContext, PolymorpheusComponent } from '@taiga-ui/polymorpheus' +import { + WwanConnectRequest, + WwanNetwork, + WwanPriority, + WwanSecurity, +} from 'src/app/services/api/api.service' +import { i18nPipe } from 'src/app/i18n/i18n.pipe' +import { provideTranslatedValidationErrors } from 'src/app/i18n/validation-errors' +import { + BAND_LABELS, + byteLength, + noControlCharacters, + PRIORITY_LABELS, + securityLabel, +} from './utils' + +export interface WwanJoinData { + radio: string + band: string + /** Whether another band's Wi-Fi stays up during the join. */ + otherBand: boolean + network?: WwanNetwork + priority?: WwanPriority +} + +@Component({ + template: ` +
+
+

{{ 'Join network' | i18n }}

+

{{ band | i18n }}

+
+
+
+ + + + + + @if (!network) { + + + + + @for (s of securities; track s) { + + } + + + } + @if (form.controls.password.enabled) { + + + + + + + } +
+ {{ 'Priority' | i18n }} + +
+
+ {{ + 'While the router is not connected to this network, its own Wi-Fi on this band is off.' + | i18n + }} + {{ + (context.data.otherBand + ? 'Join from a wired device or from the other band.' + : 'Join from a wired device.' + ) | i18n + }} +
+
+ + +
+ + `, + providers: [ + tuiTextfieldOptionsProvider({ cleaner: signal(false) }), + provideTranslatedValidationErrors({ + required: 'This field is required', + minBytes: 'Must be at least 8 characters', + maxBytes: 'Too long', + control: 'Must not contain control characters', + }), + ], + imports: [ + ReactiveFormsModule, + TuiHeader, + TuiTitle, + TuiForm, + TuiTextfield, + TuiInput, + TuiError, + TuiIcon, + TuiPassword, + TuiSelect, + TuiChevron, + TuiDataList, + TuiRadioList, + TuiNotification, + TuiButton, + TuiAutoFocus, + TuiValueChanges, + i18nPipe, + ], +}) +class WwanJoinDialog { + private readonly i18n = inject(i18nPipe) + + protected readonly context = + injectContext>() + protected readonly isMobile = inject(WA_IS_MOBILE) + protected readonly network = this.context.data.network + protected readonly band = BAND_LABELS[this.context.data.band] ?? 'Wi-Fi' + + protected readonly securities: WwanSecurity[] = [ + 'wpa2', + 'wpa2Wpa3', + 'wpa3', + 'open', + ] + protected readonly priorities: WwanPriority[] = ['backup', 'preferred'] + + protected readonly form = inject(NonNullableFormBuilder).group({ + ssid: [ + this.network?.ssid ?? '', + [Validators.required, byteLength(1, 32), noControlCharacters], + ], + security: [this.network?.security ?? ('wpa2' as WwanSecurity)], + password: [ + { value: '', disabled: this.network?.security === 'open' }, + [Validators.required, byteLength(8, 63), noControlCharacters], + ], + priority: [this.context.data.priority ?? ('backup' as WwanPriority)], + }) + + protected readonly stringifySecurity = (s: WwanSecurity): string => + securityLabel(this.i18n, s) + + protected readonly priority = ({ $implicit }: TuiContext) => + this.i18n.transform(PRIORITY_LABELS[$implicit]) + + protected onSecurity(security: WwanSecurity): void { + const { password } = this.form.controls + security === 'open' ? password.disable() : password.enable() + } + + protected join(): void { + tuiMarkControlAsTouchedAndValidate(this.form) + if (this.form.invalid) return + const { ssid, security, password, priority } = this.form.getRawValue() + this.context.completeWith({ + radio: this.context.data.radio, + ssid, + security, + password: security === 'open' ? null : password, + priority, + }) + } +} + +export const WWAN_JOIN = new PolymorpheusComponent(WwanJoinDialog) diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/index.ts b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/index.ts new file mode 100644 index 0000000000..7d6fd756e0 --- /dev/null +++ b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/index.ts @@ -0,0 +1,381 @@ +import { + Component, + computed, + effect, + inject, + linkedSignal, +} from '@angular/core' +import { NonNullableFormBuilder, ReactiveFormsModule } from '@angular/forms' +import { RouterLink } from '@angular/router' +import { TuiResponsiveDialogService } from '@taiga-ui/addon-mobile' +import type { TuiContext } from '@taiga-ui/cdk' +import { TuiButton, TuiLink, TuiNotification, TuiTitle } from '@taiga-ui/core' +import { + TUI_CONFIRM, + TuiBadge, + TuiRadioList, + TuiSegmented, + TuiStatus, +} from '@taiga-ui/kit' +import { TuiHeader } from '@taiga-ui/layout' +import { filter } from 'rxjs' +import { Footer } from 'src/app/components/footer' +import { Form } from 'src/app/components/form' +import { Summary } from 'src/app/components/summary' +import { + WwanConnectRequest, + WwanNetwork, + WwanPriority, + WwanResponse, + WwanUplink, +} from 'src/app/services/api/api.service' +import { provideFormService } from 'src/app/services/form.service' +import { i18nKey } from 'src/app/i18n/i18n.providers' +import { i18nPipe } from 'src/app/i18n/i18n.pipe' +import { LUCI_URL } from 'src/app/utils/luci' +import { WWAN_JOIN, WwanJoinData } from './dialog' +import { WwanService } from './service' +import { WwanNetworksTable } from './table' +import { BAND_LABELS, PRIORITY_LABELS } from './utils' + +interface UplinkStatus { + label: i18nKey + appearance: string +} + +function uplinkStatus({ uplink, state }: WwanResponse): UplinkStatus { + if (uplink?.stopped) { + return { label: 'Stopped', appearance: 'negative' } + } + if (!state?.associated) { + return { label: 'Not connected', appearance: 'negative' } + } + if (!state.address) { + return { label: 'Connecting', appearance: 'warning' } + } + return state.active + ? { label: 'In use', appearance: 'positive' } + : { label: 'Standing by', appearance: 'neutral' } +} + +@Component({ + template: ` + @if (service.data(); as data) { + @if (data.unmanaged.length) { +
+ {{ + 'A Wi-Fi uplink was set up in LuCI. Manage it there, or delete it there to manage the uplink here.' + | i18n + }} + + {{ 'Launch LuCI Interface' | i18n }} + +
+ } + @if (data.uplink; as uplink) { +
+

{{ 'Summary' | i18n }}

+ +
+ @if (stopMessage(); as message) { +
+
+ {{ 'Stopped' | i18n }} + + {{ message }} + {{ + 'Retrying turns the router’s own Wi-Fi on this band off again until it connects.' + | i18n + }} + +
+ + @if (uplink.security !== 'open') { + + } +
+
+
+ } @else if (!data.state?.associated) { +
+ {{ + 'The router keeps trying to connect. Until it does, its own Wi-Fi on this band is off.' + | i18n + }} +
+ } @else if (data.state?.subnetConflict) { +
+ {{ + 'This network uses the same address range as one of your own networks, so your devices cannot reach the Internet through it. Change your range under LAN Settings or Security Profiles.' + | i18n + }} +
+ } +
+
+
{{ 'Network name' | i18n }}
+ @if (status(); as s) { +
+ {{ 'Status' | i18n }} + + + {{ s.label | i18n }} + + +
+ } +
+ {{ 'Assigned IP' | i18n }} +
+
+ {{ 'Signal' | i18n }} + @if (data.state?.signal; as signal) { + {{ signal }} dBm + } +
+
+ {{ 'Band' | i18n }} + {{ band(uplink.band) | i18n }} +
+
+
+
+

{{ 'Settings' | i18n }}

+
+
+
+ {{ 'Priority' | i18n }} + +
+
+ {{ + 'While the router is not connected to this network, its own Wi-Fi on this band is off.' + | i18n + }} +
+
+
+ } @else if (!data.unmanaged.length && radios().length) { +
+
+

{{ 'Available networks' | i18n }}

+

+ {{ + 'Connect the router to another Wi-Fi network for Internet access, as a backup to the WAN port or in its place.' + | i18n + }} +

+
+ +
+ @if (networks(); as list) { +
+ } @else { +

+ {{ 'Scan to list the Wi-Fi networks this band can reach.' | i18n }} +

+ } + } @else if (!data.unmanaged.length) { +
+ {{ 'Turn on Wi-Fi to join a network.' | i18n }} + {{ 'Wi-Fi' | i18n }} +
+ } + } @else { +
+ } + `, + host: { class: 'g-page' }, + providers: [provideFormService(WwanService)], + imports: [ + ReactiveFormsModule, + RouterLink, + TuiHeader, + TuiTitle, + TuiButton, + TuiLink, + TuiNotification, + TuiBadge, + TuiStatus, + TuiRadioList, + TuiSegmented, + Footer, + Form, + Summary, + WwanNetworksTable, + i18nPipe, + ], +}) +export default class Wwan { + private readonly dialogs = inject(TuiResponsiveDialogService) + private readonly i18n = inject(i18nPipe) + + protected readonly service = inject(WwanService) + protected readonly luciUrl = LUCI_URL + protected readonly priorities: WwanPriority[] = ['backup', 'preferred'] + protected readonly form = inject(NonNullableFormBuilder).group({ + priority: ['backup' as WwanPriority], + }) + + protected readonly radios = computed( + () => this.service.data()?.radios.filter(r => r.enabled) ?? [], + ) + protected readonly radio = linkedSignal< + WwanResponse['radios'], + string | undefined + >({ + source: this.radios, + computation: (radios, previous) => + (radios.find(r => r.radio === previous?.value) ?? radios[0])?.radio, + }) + protected readonly radioIndex = computed(() => + this.radios().findIndex(r => r.radio === this.radio()), + ) + protected readonly networks = linkedSignal< + string | undefined, + WwanNetwork[] | null + >({ source: this.radio, computation: () => null }) + protected readonly stopMessage = computed(() => { + const data = this.service.data() + return data ? this.service.stopMessage(data) : null + }) + protected readonly status = computed(() => { + const data = this.service.data() + return data ? uplinkStatus(data) : null + }) + + protected readonly band = (band: string): i18nKey => + BAND_LABELS[band] ?? 'Wi-Fi' + + protected readonly priority = ({ $implicit }: TuiContext) => + this.i18n.transform(PRIORITY_LABELS[$implicit]) + + constructor() { + effect(() => { + const priority = this.service.data()?.uplink?.priority + if (priority && this.form.pristine) this.form.reset({ priority }) + }) + } + + protected async scan(): Promise { + const radio = this.radio() + if (!radio) return + const networks = await this.service.scan(radio) + if (networks && radio === this.radio()) this.networks.set(networks) + } + + protected join(network?: WwanNetwork): void { + const radio = this.radios().find(r => r.radio === this.radio()) + if (radio) this.openJoin({ radio: radio.radio, band: radio.band, network }) + } + + protected changePassword({ radio, band, ...uplink }: WwanUplink): void { + this.openJoin({ + radio, + band, + network: { + ssid: uplink.ssid, + bssid: '', + channel: null, + signal: null, + security: uplink.security, + }, + priority: uplink.priority, + }) + } + + protected async savePriority(): Promise { + if (await this.service.setPriority(this.form.getRawValue().priority)) { + this.form.markAsPristine() + } + } + + protected disconnect(): void { + this.dialogs + .open(TUI_CONFIRM, { + label: this.i18n.transform('Remove uplink?'), + data: { + content: this.i18n.transform( + 'The router will leave this network. Its Internet access then depends on the WAN port alone.', + ), + yes: this.i18n.transform('Remove uplink'), + no: this.i18n.transform('Cancel'), + }, + }) + .pipe(filter(Boolean)) + .subscribe(async () => { + if (await this.service.disconnect()) { + this.networks.set(null) + this.form.reset() + } + }) + } + + private openJoin(data: Omit): void { + this.dialogs + .open(WWAN_JOIN, { + data: { ...data, otherBand: this.radios().length > 1 }, + }) + .subscribe(async request => { + if (await this.service.connect(request)) { + this.networks.set(null) + this.form.reset({ priority: request.priority }) + } + }) + } +} diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/remote-access.ts b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/remote-access.ts new file mode 100644 index 0000000000..b11d82fc99 --- /dev/null +++ b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/remote-access.ts @@ -0,0 +1,42 @@ +import { Component } from '@angular/core' +import { TuiButton, TuiDialogContext, TuiTitle } from '@taiga-ui/core' +import { TuiForm, TuiHeader } from '@taiga-ui/layout' +import { injectContext, PolymorpheusComponent } from '@taiga-ui/polymorpheus' +import { i18nPipe } from 'src/app/i18n/i18n.pipe' + +@Component({ + template: ` +
+

{{ 'Remote Access is on' | i18n }}

+
+
+

+ {{ + 'Devices on the network the router joins can reach its web interface and SSH while Remote Access is on.' + | i18n + }} +

+
+ + +
+
+ `, + imports: [TuiHeader, TuiTitle, TuiForm, TuiButton, i18nPipe], +}) +class WwanRemoteAccessDialog { + protected readonly context = injectContext>() +} + +/** Emits whether to turn Remote Access off before joining. Completes empty on cancel. */ +export const WWAN_REMOTE_ACCESS = new PolymorpheusComponent( + WwanRemoteAccessDialog, +) diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/service.ts b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/service.ts new file mode 100644 index 0000000000..c47631c2d5 --- /dev/null +++ b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/service.ts @@ -0,0 +1,132 @@ +import { inject, Injectable } from '@angular/core' +import { TuiResponsiveDialogService } from '@taiga-ui/addon-mobile' +import { TuiNotificationService } from '@taiga-ui/core' +import { firstValueFrom } from 'rxjs' +import { FormService } from 'src/app/services/form.service' +import { + ApiService, + WwanConnectRequest, + WwanJoinOutcome, + WwanNetwork, + WwanPriority, + WwanResponse, +} from 'src/app/services/api/api.service' +import { SystemService } from 'src/app/services/system.service' +import { i18nPipe } from 'src/app/i18n/i18n.pipe' +import { fill } from 'src/app/i18n/validation-errors' +import { WWAN_REMOTE_ACCESS } from './remote-access' +import { STOP_MESSAGES, translateUplinkErrors } from './utils' + +@Injectable() +export class WwanService extends FormService { + private readonly api = inject(ApiService) + private readonly system = inject(SystemService) + private readonly i18n = inject(i18nPipe) + private readonly dialogs = inject(TuiResponsiveDialogService) + private readonly notifications = inject(TuiNotificationService) + + load(): Promise { + return this.api.wwanGet() + } + + async store(): Promise {} + + /** The radio's scan results, or null when the scan failed. */ + async scan(radio: string): Promise { + let networks: WwanNetwork[] | null = null + await this.actions.run( + async () => { + networks = await translateUplinkErrors(this.i18n, () => + this.api.wwanScan({ radio }), + ) + }, + { loading: this.i18n.transform('Scanning') }, + ) + return networks + } + + /** Resolves false when the user cancels or the join fails. */ + async connect(params: WwanConnectRequest): Promise { + return ( + (await this.confirmRemoteAccess()) && + this.join(() => this.api.wwanConnect(params)) + ) + } + + reconnect(): Promise { + return this.join(() => this.api.wwanReconnect()) + } + + /** The stopped uplink's reason, for the user. */ + stopMessage({ uplink }: WwanResponse): string | null { + return uplink?.stopped + ? fill(this.i18n.transform(STOP_MESSAGES[uplink.stopped]), { + ssid: uplink.ssid, + }) + : null + } + + setPriority(priority: WwanPriority): Promise { + return this.actions.run(async () => { + await this.api.wwanPrioritySet({ priority }) + await this.refreshAndWait() + }) + } + + disconnect(): Promise { + return this.actions.run( + async () => { + await this.api.wwanDisconnect() + await this.refreshAndWait() + }, + { + loading: this.i18n.transform('Removing uplink'), + success: this.i18n.transform('Uplink removed'), + restart: true, + }, + ) + } + + private async confirmRemoteAccess(): Promise { + if ((this.system.info()?.remoteAccess ?? 'default') === 'never') return true + const turnOff = await firstValueFrom( + this.dialogs.open(WWAN_REMOTE_ACCESS, { size: 'm' }), + { defaultValue: null }, + ) + if (turnOff === null) return false + return ( + !turnOff || + this.actions.run(async () => { + await this.api.setPreferences({ remoteAccess: 'never' }) + await this.system.refresh() + }) + ) + } + + private join(request: () => Promise): Promise { + return this.actions.run( + async () => { + const outcome = await translateUplinkErrors(this.i18n, request) + await this.refreshAndWait() + const data = this.data() + if (outcome === 'stopped') { + throw new Error( + (data && this.stopMessage(data)) ?? + this.i18n.transform('The router couldn’t join the network.'), + ) + } + this.notifications + .open( + this.i18n.transform( + outcome === 'connected' + ? 'Joined network' + : 'The router is still trying to join the network. The Summary shows the result.', + ), + { appearance: outcome === 'connected' ? 'positive' : 'info' }, + ) + .subscribe() + }, + { loading: this.i18n.transform('Joining network'), restart: true }, + ) + } +} diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/table.ts b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/table.ts new file mode 100644 index 0000000000..7ba29d03d3 --- /dev/null +++ b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/table.ts @@ -0,0 +1,85 @@ +import { Component, inject, input, output } from '@angular/core' +import { TuiTable, TuiTableDirective } from '@taiga-ui/addon-table' +import { TuiButton, TuiIcon } from '@taiga-ui/core' +import { Placeholder } from 'src/app/components/placeholder' +import { WwanNetwork, WwanSecurity } from 'src/app/services/api/api.service' +import { i18nPipe } from 'src/app/i18n/i18n.pipe' +import { securityLabel } from './utils' + +@Component({ + selector: '[wwanNetworks]', + template: ` + + + {{ 'Network name' | i18n }} + {{ 'Signal' | i18n }} + {{ 'Security' | i18n }} + {{ 'Channel' | i18n }} + + + + + @for (network of wwanNetworks(); track network.bssid || $index) { + + + @if (network.ssid) { + {{ network.ssid }} + } @else { + {{ 'Hidden network' | i18n }} + } + + + @if (network.signal !== null) { + + {{ network.signal }} dBm + } + + + @if (network.security; as security) { + {{ label(security) }} + } @else { + {{ 'Unsupported' | i18n }} + } + + {{ network.channel }} + + + + + } @empty { + + + + {{ 'No networks found' | i18n }} + + + + } + + `, + hostDirectives: [TuiTableDirective], + host: { class: 'g-table' }, + imports: [TuiTable, TuiButton, TuiIcon, Placeholder, i18nPipe], +}) +export class WwanNetworksTable { + private readonly i18n = inject(i18nPipe) + + protected readonly label = (security: WwanSecurity): string => + securityLabel(this.i18n, security) + + public readonly wwanNetworks = input([]) + public readonly join = output() + + protected signalIcon(dbm: number): string { + if (dbm >= -60) return '@tui.wifi-high' + return dbm >= -72 ? '@tui.wifi' : '@tui.wifi-low' + } +} diff --git a/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/utils.ts b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/utils.ts new file mode 100644 index 0000000000..6c429e76f2 --- /dev/null +++ b/projects/start-wrt/web/src/app/routes/wan/routes/wireless-wan/utils.ts @@ -0,0 +1,74 @@ +import { ValidatorFn } from '@angular/forms' +import { + WwanPriority, + WwanSecurity, + WwanStopReason, +} from 'src/app/services/api/api.service' +import { i18nPipe } from 'src/app/i18n/i18n.pipe' +import { i18nKey } from 'src/app/i18n/i18n.providers' + +export const BAND_LABELS: Record = { + '2g': '2.4 GHz', + '5g': '5 GHz', +} + +export const PRIORITY_LABELS: Record = { + backup: 'Backup: used while the WAN port has no connection', + preferred: + 'Preferred: used while connected, with the WAN port taking over when it drops', +} + +export const STOP_MESSAGES: Record = { + rejected: + '{ssid} didn’t accept the router, so the router stopped trying to join it. Check the password.', + unreachable: + 'The router couldn’t find {ssid}, so it stopped trying to join it. Check that the network is on and in range.', + disabled: 'The uplink to {ssid} is turned off.', +} + +/** `ErrorKind` codes in backend/ctrl/src/error.rs. */ +const ERROR_MESSAGES: Record = { + 1027: 'This band carries the Wi-Fi uplink. Remove the uplink under WAN › Wireless WAN before turning the band off.', + 1028: 'A Wi-Fi uplink was set up in LuCI. Manage it there, or delete it there to manage the uplink here.', + 1029: 'Wi-Fi on this band is off. Turn it on to join a network.', +} + +/** Rethrows a failed RPC, translated where its code has a message. */ +export async function translateUplinkErrors( + i18n: i18nPipe, + request: () => Promise, +): Promise { + try { + return await request() + } catch (e) { + const message = ERROR_MESSAGES[(e as { code?: number } | null)?.code ?? -1] + throw message ? new Error(i18n.transform(message)) : e + } +} + +const SECURITY_LABELS: Record, string> = { + wpa2: 'WPA2', + wpa2Wpa3: 'WPA2/WPA3', + wpa3: 'WPA3', +} + +export function securityLabel(i18n: i18nPipe, security: WwanSecurity): string { + return security === 'open' + ? i18n.transform('Open (no password)') + : SECURITY_LABELS[security] +} + +const encoder = new TextEncoder() + +/** Bounds the UTF-8 length. An empty value passes. */ +export function byteLength(min: number, max: number): ValidatorFn { + return ({ value }) => { + const { length } = encoder.encode(value) + if (!length) return null + if (length < min) return { minBytes: true } + return length > max ? { maxBytes: true } : null + } +} + +export const noControlCharacters: ValidatorFn = ({ value }) => + /\p{Cc}/u.test(value) ? { control: true } : null 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..202a081b07 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/wan/routes/wireless-wan/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,14 @@ const COUNTRY_CHANGE_MAX_WIDTH = 80 } + @if (uplinkNotice(); as notice) { + + }