// SPDX-License-Identifier: CPAL-1.0 // Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution // License 1.0: see LICENSE (its Exhibit A is this file's notice). //! Ianitor control: the routes repository, apply with automatic rollback, share links, API //! tokens and the REST API, on loopback only. It never serves public traffic; if it stops, //! edge keeps serving the last good config. pub mod api; pub mod caddy_guard; pub mod caddy_link; pub mod config; pub mod crash; pub mod edgelink; pub mod engine; pub mod hostspec; pub mod logger; pub mod messages; pub mod pki; pub mod pki_ctl; pub mod records; pub mod repo; pub mod shares; pub mod switch; pub mod tokens; pub mod util; use std::sync::Arc; pub use config::Config; pub use engine::Control; /// Open control, start its background tasks and serve the API until `shutdown` resolves. pub async fn serve( cfg: Config, shutdown: impl std::future::Future + Send + 'static, ) -> Result<(), String> { cfg.check().map_err(|e| e.to_string())?; let listen = cfg.listen; let ui_socket = cfg.ui.as_ref().and_then(|u| u.socket.clone()); let ctl = Control::open(cfg).await?; tokio::spawn(ctl.clone().worker()); tokio::spawn(ctl.clone().health_poller()); tokio::spawn(ctl.clone().pusher()); tokio::spawn(ctl.clone().pki_poller()); let app = api::router(api::AppState::new(ctl.clone())); if !listen.ip().is_loopback() { return Err("ianitor-control only listens on loopback".into()); } let listener = tokio::net::TcpListener::bind(listen) .await .map_err(|e| format!("cannot listen on {listen}: {e}"))?; log::info!(target: "ianitor::control", "API on http://{listen}/api/v1"); // One shutdown for both listeners. let (stop_tx, stop_rx) = tokio::sync::watch::channel(false); tokio::spawn(async move { shutdown.await; let _ = stop_tx.send(true); }); let stopped = |mut rx: tokio::sync::watch::Receiver| async move { let _ = rx.wait_for(|s| *s).await; }; let tcp = axum::serve(listener, app.clone()).with_graceful_shutdown(stopped(stop_rx.clone())); match ui_socket { None => tcp.await.map_err(|e| e.to_string())?, Some(path) => { let ui = ui_listener(&path)?; log::info!(target: "ianitor::control", "UI API on unix:{}", path.display()); let ui_app = app.layer(axum::Extension(api::ViaUiSocket)); let ui = serve_ui(ui, ui_app, stopped(stop_rx)); let (a, b) = tokio::join!(std::future::IntoFuture::into_future(tcp), ui); a.map_err(|e| e.to_string())?; b?; } } drop(ctl); Ok(()) } /// Control's UI socket: a stale socket file from an earlier run is replaced; the new one is /// 0660 (owner and group: edge and Caddy are in the ianitor group). Its directory is the /// real fence: only the ianitor group may enter it, so no other user can connect or put a /// socket of their own in its place. #[cfg(unix)] fn ui_listener(path: &std::path::Path) -> Result { use std::os::unix::fs::{FileTypeExt, PermissionsExt}; if let Ok(m) = std::fs::symlink_metadata(path) { if !m.file_type().is_socket() { return Err(format!( "{} exists and is not a socket; not replacing it", path.display() )); } std::fs::remove_file(path).map_err(|e| format!("cannot remove {}: {e}", path.display()))?; } let l = tokio::net::UnixListener::bind(path) .map_err(|e| format!("cannot listen on {}: {e}", path.display()))?; std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660)) .map_err(|e| format!("cannot set the mode of {}: {e}", path.display()))?; Ok(l) } #[cfg(unix)] async fn serve_ui( l: tokio::net::UnixListener, app: axum::Router, stop: impl std::future::Future + Send + 'static, ) -> Result<(), String> { axum::serve(l, app) .with_graceful_shutdown(stop) .await .map_err(|e| e.to_string()) } #[cfg(not(unix))] struct NoUnixListener; #[cfg(not(unix))] fn ui_listener(path: &std::path::Path) -> Result { Err(format!( "ui.socket {}: a Unix socket needs a Unix system", path.display() )) } #[cfg(not(unix))] async fn serve_ui( _l: NoUnixListener, _app: axum::Router, _stop: impl std::future::Future + Send + 'static, ) -> Result<(), String> { Ok(()) } /// Wait for Ctrl-C or SIGTERM. pub async fn stop_signal() { #[cfg(unix)] { use tokio::signal::unix::{SignalKind, signal}; let mut term = match signal(SignalKind::terminate()) { Ok(s) => s, Err(_) => { let _ = tokio::signal::ctrl_c().await; return; } }; tokio::select! { _ = tokio::signal::ctrl_c() => {} _ = term.recv() => {} } } #[cfg(not(unix))] { let _ = tokio::signal::ctrl_c().await; } } /// For tests: the router over an opened control. pub fn app(ctl: Arc) -> axum::Router { api::router(api::AppState::new(ctl)) }