feat: support multiple echoip URLs with fallback

Rename ifconfig_url to echoip_urls and iterate through configured URLs,
falling back to the next one on failure. Reduces timeout per attempt
from 10s to 5s.
This commit is contained in:
Aiden McClelland
2026-03-11 15:14:20 -06:00
parent 324f9d17cd
commit 90b73dd320
5 changed files with 111 additions and 62 deletions

View File

@@ -1592,6 +1592,13 @@ net.gateway.cannot-delete-without-connection:
fr_FR: "Impossible de supprimer l'appareil sans connexion active" fr_FR: "Impossible de supprimer l'appareil sans connexion active"
pl_PL: "Nie można usunąć urządzenia bez aktywnego połączenia" pl_PL: "Nie można usunąć urządzenia bez aktywnego połączenia"
net.gateway.no-configured-echoip-urls:
en_US: "No configured echoip URLs"
de_DE: "Keine konfigurierten EchoIP-URLs"
es_ES: "No hay URLs de echoip configuradas"
fr_FR: "Aucune URL echoip configurée"
pl_PL: "Brak skonfigurowanych adresów URL echoip"
# net/dns.rs # net/dns.rs
net.dns.timeout-updating-catalog: net.dns.timeout-updating-catalog:
en_US: "timed out waiting to update dns catalog" en_US: "timed out waiting to update dns catalog"
@@ -2753,6 +2760,13 @@ help.arg.download-directory:
fr_FR: "Chemin du répertoire de téléchargement" fr_FR: "Chemin du répertoire de téléchargement"
pl_PL: "Ścieżka katalogu do pobrania" pl_PL: "Ścieżka katalogu do pobrania"
help.arg.echoip-urls:
en_US: "Echo IP service URLs for external IP detection"
de_DE: "Echo-IP-Dienst-URLs zur externen IP-Erkennung"
es_ES: "URLs del servicio Echo IP para detección de IP externa"
fr_FR: "URLs du service Echo IP pour la détection d'IP externe"
pl_PL: "Adresy URL usługi Echo IP do wykrywania zewnętrznego IP"
help.arg.emulate-missing-arch: help.arg.emulate-missing-arch:
en_US: "Emulate missing architecture using this one" en_US: "Emulate missing architecture using this one"
de_DE: "Fehlende Architektur mit dieser emulieren" de_DE: "Fehlende Architektur mit dieser emulieren"
@@ -5260,6 +5274,13 @@ about.set-country:
fr_FR: "Définir le pays" fr_FR: "Définir le pays"
pl_PL: "Ustaw kraj" pl_PL: "Ustaw kraj"
about.set-echoip-urls:
en_US: "Set the Echo IP service URLs"
de_DE: "Die Echo-IP-Dienst-URLs festlegen"
es_ES: "Establecer las URLs del servicio Echo IP"
fr_FR: "Définir les URLs du service Echo IP"
pl_PL: "Ustaw adresy URL usługi Echo IP"
about.set-hostname: about.set-hostname:
en_US: "Set the server hostname" en_US: "Set the server hostname"
de_DE: "Den Server-Hostnamen festlegen" de_DE: "Den Server-Hostnamen festlegen"

View File

@@ -146,7 +146,7 @@ impl Public {
zram: true, zram: true,
governor: None, governor: None,
smtp: None, smtp: None,
ifconfig_url: default_ifconfig_url(), echoip_urls: default_echoip_urls(),
ram: 0, ram: 0,
devices: Vec::new(), devices: Vec::new(),
kiosk, kiosk,
@@ -168,8 +168,11 @@ fn get_platform() -> InternedString {
(&*PLATFORM).into() (&*PLATFORM).into()
} }
pub fn default_ifconfig_url() -> Url { pub fn default_echoip_urls() -> Vec<Url> {
"https://ifconfig.co".parse().unwrap() vec![
"https://ipconfig.io".parse().unwrap(),
"https://ifconfig.co".parse().unwrap(),
]
} }
#[derive(Debug, Deserialize, Serialize, HasModel, TS)] #[derive(Debug, Deserialize, Serialize, HasModel, TS)]
@@ -206,9 +209,9 @@ pub struct ServerInfo {
pub zram: bool, pub zram: bool,
pub governor: Option<Governor>, pub governor: Option<Governor>,
pub smtp: Option<SmtpValue>, pub smtp: Option<SmtpValue>,
#[serde(default = "default_ifconfig_url")] #[serde(default = "default_echoip_urls")]
#[ts(type = "string")] #[ts(type = "string[]")]
pub ifconfig_url: Url, pub echoip_urls: Vec<Url>,
#[ts(type = "number")] #[ts(type = "number")]
pub ram: u64, pub ram: u64,
pub devices: Vec<LshwDevice>, pub devices: Vec<LshwDevice>,

View File

@@ -400,10 +400,10 @@ pub fn server<C: Context>() -> ParentHandler<C> {
.with_call_remote::<CliContext>(), .with_call_remote::<CliContext>(),
) )
.subcommand( .subcommand(
"set-ifconfig-url", "set-echoip-urls",
from_fn_async(system::set_ifconfig_url) from_fn_async(system::set_echoip_urls)
.no_display() .no_display()
.with_about("about.set-ifconfig-url") .with_about("about.set-echoip-urls")
.with_call_remote::<CliContext>(), .with_call_remote::<CliContext>(),
) )
.subcommand( .subcommand(

View File

@@ -205,7 +205,7 @@ pub async fn check_port(
CheckPortParams { port, gateway }: CheckPortParams, CheckPortParams { port, gateway }: CheckPortParams,
) -> Result<CheckPortRes, Error> { ) -> Result<CheckPortRes, Error> {
let db = ctx.db.peek().await; let db = ctx.db.peek().await;
let base_url = db.as_public().as_server_info().as_ifconfig_url().de()?; let base_urls = db.as_public().as_server_info().as_echoip_urls().de()?;
let gateways = db let gateways = db
.as_public() .as_public()
.as_server_info() .as_server_info()
@@ -240,22 +240,41 @@ pub async fn check_port(
let client = reqwest::Client::builder(); let client = reqwest::Client::builder();
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
let client = client.interface(gateway.as_str()); let client = client.interface(gateway.as_str());
let url = base_url let client = client.build()?;
.join(&format!("/port/{port}"))
.with_kind(ErrorKind::ParseUrl)?; let mut res = None;
let IfconfigPortRes { for base_url in base_urls {
let url = base_url
.join(&format!("/port/{port}"))
.with_kind(ErrorKind::ParseUrl)?;
res = Some(
async {
client
.get(url)
.timeout(Duration::from_secs(5))
.send()
.await?
.error_for_status()?
.json()
.await
}
.await,
);
if res.as_ref().map_or(false, |r| r.is_ok()) {
break;
}
}
let Some(IfconfigPortRes {
ip, ip,
port, port,
reachable: open_externally, reachable: open_externally,
} = client }) = res.transpose()?
.build()? else {
.get(url) return Err(Error::new(
.timeout(Duration::from_secs(10)) eyre!("{}", t!("net.gateway.no-configured-echoip-urls")),
.send() ErrorKind::Network,
.await? ));
.error_for_status()? };
.json()
.await?;
let hairpinning = tokio::time::timeout( let hairpinning = tokio::time::timeout(
Duration::from_secs(5), Duration::from_secs(5),
@@ -761,7 +780,7 @@ async fn get_wan_ipv4(iface: &str, base_url: &Url) -> Result<Option<Ipv4Addr>, E
let text = client let text = client
.build()? .build()?
.get(url) .get(url)
.timeout(Duration::from_secs(10)) .timeout(Duration::from_secs(5))
.send() .send()
.await? .await?
.error_for_status()? .error_for_status()?
@@ -857,7 +876,7 @@ async fn watch_ip(
.fuse() .fuse()
}); });
let mut prev_attempt: Option<Instant> = None; let mut echoip_ratelimit_state: BTreeMap<Url, Instant> = BTreeMap::new();
loop { loop {
until until
@@ -967,7 +986,7 @@ async fn watch_ip(
&dhcp4_proxy, &dhcp4_proxy,
&policy_guard, &policy_guard,
&iface, &iface,
&mut prev_attempt, &mut echoip_ratelimit_state,
db, db,
write_to, write_to,
device_type, device_type,
@@ -1174,7 +1193,7 @@ async fn poll_ip_info(
dhcp4_proxy: &Option<Dhcp4ConfigProxy<'_>>, dhcp4_proxy: &Option<Dhcp4ConfigProxy<'_>>,
policy_guard: &Option<PolicyRoutingCleanup>, policy_guard: &Option<PolicyRoutingCleanup>,
iface: &GatewayId, iface: &GatewayId,
prev_attempt: &mut Option<Instant>, echoip_ratelimit_state: &mut BTreeMap<Url, Instant>,
db: Option<&TypedPatchDb<Database>>, db: Option<&TypedPatchDb<Database>>,
write_to: &Watch<OrdMap<GatewayId, NetworkInterfaceInfo>>, write_to: &Watch<OrdMap<GatewayId, NetworkInterfaceInfo>>,
device_type: Option<NetworkInterfaceType>, device_type: Option<NetworkInterfaceType>,
@@ -1221,43 +1240,49 @@ async fn poll_ip_info(
apply_policy_routing(guard, iface, &lan_ip).await?; apply_policy_routing(guard, iface, &lan_ip).await?;
} }
let ifconfig_url = if let Some(db) = db { let echoip_urls = if let Some(db) = db {
db.peek() db.peek()
.await .await
.as_public() .as_public()
.as_server_info() .as_server_info()
.as_ifconfig_url() .as_echoip_urls()
.de() .de()
.unwrap_or_else(|_| crate::db::model::public::default_ifconfig_url()) .unwrap_or_else(|_| crate::db::model::public::default_echoip_urls())
} else { } else {
crate::db::model::public::default_ifconfig_url() crate::db::model::public::default_echoip_urls()
}; };
let wan_ip = if prev_attempt.map_or(true, |i| i.elapsed() > Duration::from_secs(300)) let mut wan_ip = None;
&& !subnets.is_empty() for echoip_url in echoip_urls {
&& !matches!( let wan_ip = if echoip_ratelimit_state
device_type, .get(&echoip_url)
Some(NetworkInterfaceType::Bridge | NetworkInterfaceType::Loopback) .map_or(true, |i| i.elapsed() > Duration::from_secs(300))
) { && !subnets.is_empty()
let res = match get_wan_ipv4(iface.as_str(), &ifconfig_url).await { && !matches!(
Ok(a) => a, device_type,
Err(e) => { Some(NetworkInterfaceType::Bridge | NetworkInterfaceType::Loopback)
tracing::error!( ) {
"{}", match get_wan_ipv4(iface.as_str(), &echoip_url).await {
t!( Ok(a) => {
"net.gateway.failed-to-determine-wan-ip", wan_ip = a;
iface = iface.to_string(), }
error = e.to_string() Err(e) => {
) tracing::error!(
); "{}",
tracing::debug!("{e:?}"); t!(
None "net.gateway.failed-to-determine-wan-ip",
iface = iface.to_string(),
error = e.to_string()
)
);
tracing::debug!("{e:?}");
}
};
echoip_ratelimit_state.insert(echoip_url, Instant::now());
if wan_ip.is_some() {
break;
} }
}; };
*prev_attempt = Some(Instant::now()); }
res
} else {
None
};
let mut ip_info = IpInfo { let mut ip_info = IpInfo {
name: name.clone(), name: name.clone(),
scope_id, scope_id,

View File

@@ -1172,21 +1172,21 @@ pub async fn clear_system_smtp(ctx: RpcContext) -> Result<(), Error> {
} }
#[derive(Debug, Clone, Deserialize, Serialize, Parser)] #[derive(Debug, Clone, Deserialize, Serialize, Parser)]
pub struct SetIfconfigUrlParams { pub struct SetEchoipUrlsParams {
#[arg(help = "help.arg.ifconfig-url")] #[arg(help = "help.arg.echoip-urls")]
pub url: url::Url, pub urls: Vec<url::Url>,
} }
pub async fn set_ifconfig_url( pub async fn set_echoip_urls(
ctx: RpcContext, ctx: RpcContext,
SetIfconfigUrlParams { url }: SetIfconfigUrlParams, SetEchoipUrlsParams { urls }: SetEchoipUrlsParams,
) -> Result<(), Error> { ) -> Result<(), Error> {
ctx.db ctx.db
.mutate(|db| { .mutate(|db| {
db.as_public_mut() db.as_public_mut()
.as_server_info_mut() .as_server_info_mut()
.as_ifconfig_url_mut() .as_echoip_urls_mut()
.ser(&url) .ser(&urls)
}) })
.await .await
.result .result