diff --git a/Cargo.lock b/Cargo.lock index 0a461cb..4bc91fe 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1328,6 +1328,7 @@ dependencies = [ "toml", "url", "utoipa", + "windows-service", ] [[package]] @@ -1359,6 +1360,7 @@ dependencies = [ "rustls", "serde_json", "tokio", + "toml", ] [[package]] @@ -3553,6 +3555,12 @@ dependencies = [ "rustls-pki-types", ] +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + [[package]] name = "winapi-util" version = "0.1.11" @@ -3568,6 +3576,17 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-service" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2" +dependencies = [ + "bitflags", + "widestring", + "windows-sys 0.61.2", +] + [[package]] name = "windows-sys" version = "0.52.0" diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 1ea1061..0faee82 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -45,6 +45,10 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] } # The offline root CLI asks for its passphrase without echo. rpassword = "7" +# Windows Server, Caddy mode: the service control manager starts control and the guard. +[target.'cfg(windows)'.dependencies] +windows-service = "0.8" + [dev-dependencies] ianitor-testkit.workspace = true p12-keystore = "0.4" diff --git a/crates/control/src/caddy_guard.rs b/crates/control/src/caddy_guard.rs index e931672..10b1039 100644 --- a/crates/control/src/caddy_guard.rs +++ b/crates/control/src/caddy_guard.rs @@ -127,15 +127,12 @@ async fn revert(cfg: &Config, why: &str) -> Result { return Ok(false); } let loaded = async { - let sock = cfg - .caddy_compile() - .caddy_admin_socket - .clone() - .ok_or("no caddy_admin_socket is configured")?; + let sock = crate::caddy_link::Admin::from_compile(cfg.caddy_compile()) + .ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured")?; let text = std::fs::read(&cfg.caddy.config) .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; - crate::caddy_link::load(Path::new(&sock), &text).await?; - if !crate::caddy_link::runs(Path::new(&sock), &text).await? { + crate::caddy_link::load(&sock, &text).await?; + if !crate::caddy_link::runs(&sock, &text).await? { return Err("Caddy took caddy.json but does not run it".to_owned()); } Ok::<_, String>(()) diff --git a/crates/control/src/caddy_link.rs b/crates/control/src/caddy_link.rs index 4dcc777..89fc5cb 100644 --- a/crates/control/src/caddy_link.rs +++ b/crates/control/src/caddy_link.rs @@ -3,60 +3,116 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Control's side of the Caddy fallback while it serves (Mark, 2026-11-08: changes keep -//! working under Caddy): loading a config through Caddy's admin API on its Unix socket +//! working under Caddy): loading a config through Caddy's admin API on its Unix socket, or on +//! loopback TCP where there are no Unix sockets (Windows Caddy mode, T4) //! (`POST /load`, the whole JSON) and reading back what runs (`GET /config/`), probing a host //! *through* Caddy ("does Caddy answer at all") and its upstreams directly (the health watch, //! judged like edge's), and the certificate Caddy serves. use std::net::SocketAddr; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + const TIMEOUT: Duration = Duration::from_secs(10); -/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). -async fn admin(socket: &Path, request: &[u8]) -> Result<(u16, Vec), String> { - #[cfg(unix)] - { - use tokio::io::{AsyncReadExt, AsyncWriteExt}; - let exchange = async { - let mut s = tokio::net::UnixStream::connect(socket).await?; +/// Where Caddy's admin API listens: a Unix socket (Linux, mode 0660), or loopback TCP +/// (Windows, where control and Caddy are the only services and the port is on 127.0.0.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Admin { + Unix(PathBuf), + Tcp(SocketAddr), +} + +impl Admin { + /// From the compile facts: the socket when there is one, else a loopback TCP address. + pub fn from_compile(c: &crate::config::Compile) -> Option { + match (&c.caddy_admin_socket, c.caddy_admin) { + (Some(s), _) => Some(Admin::Unix(PathBuf::from(s))), + (None, Some(a)) if a.ip().is_loopback() => Some(Admin::Tcp(a)), + _ => None, + } + } + + /// The `Host` header Caddy's admin API accepts (its origin check). + fn host(&self) -> String { + match self { + Admin::Unix(_) => "localhost".into(), + Admin::Tcp(a) => a.to_string(), + } + } +} + +impl From<&Path> for Admin { + fn from(p: &Path) -> Admin { + Admin::Unix(p.to_owned()) + } +} + +async fn exchange(admin: &Admin, request: &[u8]) -> std::io::Result> { + let mut buf = Vec::new(); + match admin { + #[cfg(unix)] + Admin::Unix(p) => { + let mut s = tokio::net::UnixStream::connect(p).await?; s.write_all(request).await?; - let mut buf = Vec::new(); s.read_to_end(&mut buf).await?; - Ok::<_, std::io::Error>(buf) - }; - let buf = tokio::time::timeout(TIMEOUT, exchange) - .await - .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? - .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; - let split = buf + } + #[cfg(not(unix))] + Admin::Unix(_) => { + return Err(std::io::Error::other( + "Caddy's admin socket needs Unix; set caddy_admin = \"127.0.0.1:2019\" instead", + )); + } + Admin::Tcp(a) => { + let mut s = tokio::net::TcpStream::connect(a).await?; + s.write_all(request).await?; + s.read_to_end(&mut buf).await?; + } + } + Ok(buf) +} + +/// One request to Caddy's admin API (HTTP/1.0: the answer is never chunked). `request` has +/// `{host}` where the Host header value goes. +async fn admin(admin: &Admin, request: &[u8]) -> Result<(u16, Vec), String> { + let host = admin.host(); + let request = { + let split = request .windows(4) .position(|w| w == b"\r\n\r\n") - .ok_or("no answer from Caddy's admin API")?; - let head = String::from_utf8_lossy(&buf[..split]); - let status: u16 = head - .split(' ') - .nth(1) - .and_then(|s| s.parse().ok()) - .ok_or("no answer from Caddy's admin API")?; - Ok((status, buf[split + 4..].to_vec())) - } - #[cfg(not(unix))] - { - let _ = (socket, request); - Err("Caddy's admin socket needs Unix".into()) - } + .unwrap_or(request.len()); + let head = String::from_utf8_lossy(&request[..split]).replace("{host}", &host); + let mut r = head.into_bytes(); + r.extend_from_slice(&request[split..]); + r + }; + let buf = tokio::time::timeout(TIMEOUT, exchange(admin, &request)) + .await + .map_err(|_| "Caddy's admin API did not answer within 10 s".to_owned())? + .map_err(|e| format!("Caddy's admin API cannot be reached: {e}"))?; + let split = buf + .windows(4) + .position(|w| w == b"\r\n\r\n") + .ok_or("no answer from Caddy's admin API")?; + let head = String::from_utf8_lossy(&buf[..split]); + let status: u16 = head + .split(' ') + .nth(1) + .and_then(|s| s.parse().ok()) + .ok_or("no answer from Caddy's admin API")?; + Ok((status, buf[split + 4..].to_vec())) } /// Load a full Caddy JSON config. Caddy swaps it in gracefully or refuses it (and keeps the /// old one). `Cache-Control: must-revalidate` makes Caddy load it even when it is the same as /// the running one, so certificate and device files are read again (without it an identical /// config is a no-op: QC round 2, B1; `qc_reloading_the_same_caddy_json_rereads_the_certificate_files`). -pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { +pub async fn load(socket: &Admin, config: &[u8]) -> Result<(), String> { let mut req = format!( - "POST /load HTTP/1.0\r\nHost: localhost\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n", + "POST /load HTTP/1.0\r\nHost: {{host}}\r\nContent-Type: application/json\r\nCache-Control: must-revalidate\r\nContent-Length: {}\r\n\r\n", config.len() ) .into_bytes(); @@ -77,8 +133,8 @@ pub async fn load(socket: &Path, config: &[u8]) -> Result<(), String> { } /// The config Caddy runs now. -pub async fn running_config(socket: &Path) -> Result { - let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: localhost\r\n\r\n").await?; +pub async fn running_config(socket: &Admin) -> Result { + let (status, body) = admin(socket, b"GET /config/ HTTP/1.0\r\nHost: {host}\r\n\r\n").await?; if status != 200 { return Err(format!( "Caddy's admin API answered {status} to GET /config/" @@ -88,7 +144,7 @@ pub async fn running_config(socket: &Path) -> Result } /// Whether Caddy runs exactly this config (as JSON values, so formatting does not matter). -pub async fn runs(socket: &Path, config: &[u8]) -> Result { +pub async fn runs(socket: &Admin, config: &[u8]) -> Result { let want: serde_json::Value = serde_json::from_slice(config).map_err(|e| format!("not JSON: {e}"))?; Ok(running_config(socket).await? == want) diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs index 9b61bee..36bb810 100644 --- a/crates/control/src/engine/caddy_apply.rs +++ b/crates/control/src/engine/caddy_apply.rs @@ -42,13 +42,10 @@ struct Rule { } impl Control { - /// Caddy's admin socket, from `[compile_caddy]` (or `[compile]`). - pub fn caddy_socket(&self) -> Option { - self.cfg - .caddy_compile() - .caddy_admin_socket - .as_ref() - .map(std::path::PathBuf::from) + /// Caddy's admin API, from `[compile_caddy]` (or `[compile]`): its Unix socket, or its + /// loopback TCP address on Windows. + pub fn caddy_socket(&self) -> Option { + caddy_link::Admin::from_compile(self.cfg.caddy_compile()) } /// Load caddy.json (the last good config) into the running Caddy, even when it is the @@ -56,7 +53,7 @@ impl Control { pub async fn caddy_reload(&self) -> Result<(), String> { let sock = self .caddy_socket() - .ok_or("no caddy_admin_socket is configured, so Caddy cannot be told")?; + .ok_or("no caddy_admin_socket (or loopback caddy_admin) is configured, so Caddy cannot be told")?; let text = std::fs::read(&self.cfg.caddy.config) .map_err(|e| format!("cannot read {}: {e}", self.cfg.caddy.config.display()))?; caddy_link::load(&sock, &text).await?; @@ -334,7 +331,7 @@ impl Control { async fn caddy_watch( &self, id: &str, - sock: &std::path::Path, + sock: &caddy_link::Admin, trial: &str, judged: &[String], rules: &BTreeMap, diff --git a/crates/control/src/logger.rs b/crates/control/src/logger.rs index 89e01ea..6efb682 100644 --- a/crates/control/src/logger.rs +++ b/crates/control/src/logger.rs @@ -12,6 +12,8 @@ use log::{Level, LevelFilter, Log, Metadata, Record}; struct Stderr { own: LevelFilter, + /// `$IANITOR_LOG_FILE` or `--log-file`: append here instead of stderr (Windows services). + file: Option>, } impl Log for Stderr { @@ -33,12 +35,27 @@ impl Log for Stderr { Level::Debug => "DEBUG", Level::Trace => "TRACE", }; - let _ = writeln!( - std::io::stderr().lock(), - "{lvl} {}: {}", - r.target(), - r.args() - ); + match &self.file { + Some(f) => { + if let Ok(mut f) = f.lock() { + let _ = writeln!( + f, + "{} {lvl} {}: {}", + crate::util::rfc3339(crate::util::now()), + r.target(), + r.args() + ); + } + } + None => { + let _ = writeln!( + std::io::stderr().lock(), + "{lvl} {}: {}", + r.target(), + r.args() + ); + } + } } } @@ -48,6 +65,22 @@ impl Log for Stderr { } pub fn init(level: Option<&str>) { + init_to( + level, + std::env::var_os("IANITOR_LOG_FILE").map(std::path::PathBuf::from), + ); +} + +/// Like [`init`], appending to `file` when given. +pub fn init_to(level: Option<&str>, file: Option) { + let file = file.and_then(|p| { + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(p) + .ok() + .map(std::sync::Mutex::new) + }); let own = match level.map(str::to_ascii_lowercase).as_deref() { Some("error") => LevelFilter::Error, Some("warn") => LevelFilter::Warn, @@ -55,7 +88,7 @@ pub fn init(level: Option<&str>) { Some("trace") => LevelFilter::Trace, _ => LevelFilter::Info, }; - if log::set_boxed_logger(Box::new(Stderr { own })).is_ok() { + if log::set_boxed_logger(Box::new(Stderr { own, file })).is_ok() { log::set_max_level(own); } } diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index f388320..46bfb66 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -15,6 +15,7 @@ //! ianitor-control ca init --out [--passphrase-file ] the offline root (never on the server) //! ianitor-control ca sign --root --csr --out [--yes] sign an intermediate offline //! ianitor-control check --config check the config and exit +//! ianitor-control service control|caddy-guard --config [--log-file ] Windows service //! ``` //! The log level comes from `$IANITOR_LOG`. As `GIT_ASKPASS` (with `$IANITOR_ASKPASS=1`), //! the binary answers git's prompt from the push credential file. @@ -25,6 +26,8 @@ use std::process::ExitCode; use ianitor_control::{Config, logger, tokens::Tokens}; mod dev; +#[cfg(windows)] +mod winsvc; fn usage() -> ExitCode { eprintln!( @@ -387,8 +390,32 @@ fn main() -> ExitCode { if std::env::var("IANITOR_ASKPASS").as_deref() == Ok("1") { return askpass(); } - logger::init(std::env::var("IANITOR_LOG").ok().as_deref()); let args: Vec = std::env::args().skip(1).collect(); + let log_file = args + .iter() + .position(|a| a == "--log-file") + .and_then(|i| args.get(i + 1)) + .map(PathBuf::from); + match log_file { + Some(f) => logger::init_to(std::env::var("IANITOR_LOG").ok().as_deref(), Some(f)), + None => logger::init(std::env::var("IANITOR_LOG").ok().as_deref()), + } + // Windows Server, Caddy mode: started by the service control manager. + if args.first().map(String::as_str) == Some("service") { + #[cfg(windows)] + return match winsvc::run(&args[1..]) { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("ianitor-control: {e}"); + ExitCode::FAILURE + } + }; + #[cfg(not(windows))] + { + eprintln!("ianitor-control: `service` is for Windows; use the systemd units on Linux"); + return ExitCode::FAILURE; + } + } let rt = match tokio::runtime::Builder::new_multi_thread() .enable_all() .build() diff --git a/crates/control/src/winsvc.rs b/crates/control/src/winsvc.rs new file mode 100644 index 0000000..7e42c3a --- /dev/null +++ b/crates/control/src/winsvc.rs @@ -0,0 +1,109 @@ +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +//! Windows Server, Caddy mode (Fabrica docs/32_coherence.md ยง2.5, T4): what the service +//! control manager starts. `ianitor-control service control --config ` is the control +//! plane, `ianitor-control service caddy-guard --config ` the Caddy trial deadline guard +//! (its own service, so a hung or crashed control cannot leave Caddy on an unconfirmed +//! trial). Both stop cleanly on the SCM's Stop. `deploy/windows/install.ps1` registers them. +//! Logs go to the file given with `--log-file` (stderr goes nowhere under the SCM). + +use std::ffi::OsString; +use std::sync::OnceLock; +use std::time::Duration; + +use windows_service::service::{ + ServiceControl, ServiceControlAccept, ServiceExitCode, ServiceState, ServiceStatus, ServiceType, +}; +use windows_service::service_control_handler::{self, ServiceControlHandlerResult}; +use windows_service::{define_windows_service, service_dispatcher}; + +static ARGS: OnceLock> = OnceLock::new(); + +define_windows_service!(ffi_service_main, service_main); + +/// Hand this process to the service control manager (blocks until the service stops). +pub fn run(args: &[String]) -> Result<(), String> { + let _ = ARGS.set(args.to_vec()); + // The name is ignored for a service in its own process. + service_dispatcher::start("IanitorControl", ffi_service_main) + .map_err(|e| format!("not started by the service control manager ({e}); run it as a service, or use --config to run it in a console")) +} + +fn status(state: ServiceState, code: u32) -> ServiceStatus { + ServiceStatus { + service_type: ServiceType::OWN_PROCESS, + current_state: state, + controls_accepted: if state == ServiceState::Running { + ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN + } else { + ServiceControlAccept::empty() + }, + exit_code: ServiceExitCode::Win32(code), + checkpoint: 0, + wait_hint: Duration::from_secs(10), + process_id: None, + } +} + +fn service_main(_: Vec) { + let args = ARGS.get().cloned().unwrap_or_default(); + let (tx, rx) = tokio::sync::oneshot::channel::<()>(); + let tx = std::sync::Mutex::new(Some(tx)); + let handler = move |c| match c { + ServiceControl::Stop | ServiceControl::Shutdown => { + if let Ok(mut t) = tx.lock() + && let Some(t) = t.take() + { + let _ = t.send(()); + } + ServiceControlHandlerResult::NoError + } + ServiceControl::Interrogate => ServiceControlHandlerResult::NoError, + _ => ServiceControlHandlerResult::NotImplemented, + }; + let Ok(h) = service_control_handler::register("IanitorControl", handler) else { + return; + }; + let _ = h.set_service_status(status(ServiceState::Running, 0)); + let result = serve(&args, rx); + if let Err(e) = &result { + log::error!(target: "ianitor::service", "{e}"); + } + let _ = h.set_service_status(status(ServiceState::Stopped, u32::from(result.is_err()))); +} + +fn serve(args: &[String], stop: tokio::sync::oneshot::Receiver<()>) -> Result<(), String> { + let what = args.first().map(String::as_str).unwrap_or("control"); + let config = args + .iter() + .position(|a| a == "--config") + .and_then(|i| args.get(i + 1)) + .ok_or("service: --config is required")?; + let cfg = + ianitor_control::Config::load(std::path::Path::new(config)).map_err(|e| e.to_string())?; + let rt = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .build() + .map_err(|e| e.to_string())?; + rt.block_on(async move { + match what { + "control" => { + ianitor_control::serve(cfg, async { + let _ = stop.await; + }) + .await + } + "caddy-guard" => { + tokio::select! { + r = ianitor_control::caddy_guard::run(cfg) => r, + _ = stop => Ok(()), + } + } + other => Err(format!( + "service: unknown part {other:?} (control or caddy-guard)" + )), + } + }) +}