From 64b675e61fc1b5f6678396e2c8b6ca84fe402fe3 Mon Sep 17 00:00:00 2001 From: Jean Date: Fri, 17 Jul 2026 10:46:12 +0000 Subject: [PATCH] operserv: REHASH reloads config live without a restart --- api/src/lib.rs | 12 +++++++ modules/operserv/src/lib.rs | 4 +++ modules/operserv/src/rehash.rs | 15 +++++++++ modules/protocol/inspircd/src/lib.rs | 2 +- src/engine/mod.rs | 50 ++++++++++++++++++++++++++++ src/engine/tests.rs | 38 +++++++++++++++++++++ src/link.rs | 5 +++ src/main.rs | 1 + 8 files changed, 126 insertions(+), 1 deletion(-) create mode 100644 modules/operserv/src/rehash.rs diff --git a/api/src/lib.rs b/api/src/lib.rs index d4560c2..f31518e 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -169,6 +169,11 @@ pub enum NetAction { // link layer exits cleanly; `restart` exits non-zero so a supervisor (systemd // Restart=) brings it back. Never serialized. Shutdown { restart: bool, reason: String }, + // Internal only: re-read config.toml and apply the reloadable settings to the + // running engine (OperServ REHASH). The link layer resolves it against the + // engine and sends the outcome back to `requester` from `agent`. Never + // serialized as-is. + Rehash { requester: String, agent: String }, } // How to answer a registration once its credentials have been derived. @@ -386,6 +391,13 @@ impl ServiceCtx { self.actions.push(NetAction::Shutdown { restart, reason: reason.into() }); } + // Re-read config.toml and apply the reloadable settings live (OperServ REHASH). + // The engine resolves this off the command path and notices `requester` from + // `agent` with the outcome. + pub fn rehash(&mut self, agent: &str, requester: &str) { + self.actions.push(NetAction::Rehash { requester: requester.to_string(), agent: agent.to_string() }); + } + // Hand a password change to the engine to finish: its derivation runs off the // reactor, then the engine commits it and notices `uid`, sourced from `agent`. pub fn defer_password(&mut self, account: impl Into, password: impl Into, agent: impl Into, uid: impl Into) { diff --git a/modules/operserv/src/lib.rs b/modules/operserv/src/lib.rs index 5afdbdc..6bf7fcb 100644 --- a/modules/operserv/src/lib.rs +++ b/modules/operserv/src/lib.rs @@ -39,6 +39,8 @@ mod logsearch; mod defcon; #[path = "shutdown.rs"] mod shutdown; +#[path = "rehash.rs"] +mod rehash; #[path = "set.rs"] mod set; @@ -95,6 +97,7 @@ impl Service for OperServ { Some(cmd) if cmd.eq_ignore_ascii_case("SET") => set::handle(me, from, args, ctx, db), Some(cmd) if cmd.eq_ignore_ascii_case("SHUTDOWN") => shutdown::handle(me, from, false, args, ctx), Some(cmd) if cmd.eq_ignore_ascii_case("RESTART") => shutdown::handle(me, from, true, args, ctx), + Some(cmd) if cmd.eq_ignore_ascii_case("REHASH") => rehash::handle(me, from, ctx), Some(cmd) if cmd.eq_ignore_ascii_case("HELP") => echo_api::help(me, from, ctx, BLURB, TOPICS, args.get(1).copied()), None => echo_api::help(me, from, ctx, BLURB, TOPICS, None), Some(other) => ctx.notice(me, from.uid, format!("I don't know \x02{other}\x02. Try \x02HELP\x02.")), @@ -131,4 +134,5 @@ const TOPICS: &[HelpEntry] = &[ HelpEntry { cmd: "SET", summary: "services-wide settings", detail: "Syntax: \x02SET READONLY {ON|OFF}\x02\nToggles read-only lockdown: while on, no registrations or changes are accepted." }, HelpEntry { cmd: "SHUTDOWN", summary: "stop services", detail: "Syntax: \x02SHUTDOWN [reason]\x02\nStops the services process. It stays down until restarted." }, HelpEntry { cmd: "RESTART", summary: "restart services", detail: "Syntax: \x02RESTART [reason]\x02\nRestarts the services process (a supervisor respawns it)." }, + HelpEntry { cmd: "REHASH", summary: "reload the configuration", detail: "Syntax: \x02REHASH\x02\nRe-reads config.toml and applies the settings that are safe to change while linked (opers, standard-replies, services channel, service oper-type, expiry, session limits) without a restart — no relink, no user disruption. Server identity, service umodes and the keycard endpoint still need a RESTART." }, ]; diff --git a/modules/operserv/src/rehash.rs b/modules/operserv/src/rehash.rs new file mode 100644 index 0000000..c19d36c --- /dev/null +++ b/modules/operserv/src/rehash.rs @@ -0,0 +1,15 @@ +use echo_api::{Priv, Sender, ServiceCtx}; + +// REHASH: re-read config.toml and apply the settings that are safe to change +// while linked (opers, standard-replies, services channel, service oper-type, +// expiry, session limits) without restarting — so no relink and no user +// disruption. Admin-only. Server identity, service umodes and the keycard +// endpoint still need a RESTART. The engine does the re-read off the command +// path and notices the outcome (or a parse error, keeping the old config). +pub fn handle(me: &str, from: &Sender, ctx: &mut ServiceCtx) { + if !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, "Access denied — REHASH needs the \x02admin\x02 privilege."); + return; + } + ctx.rehash(me, from.uid); +} diff --git a/modules/protocol/inspircd/src/lib.rs b/modules/protocol/inspircd/src/lib.rs index ae7f003..ae51d28 100644 --- a/modules/protocol/inspircd/src/lib.rs +++ b/modules/protocol/inspircd/src/lib.rs @@ -431,7 +431,7 @@ impl Protocol for InspIrcd { NetAction::Squit { target, reason } => vec![self.sourced(format!("SQUIT {} :{}", target, reason))], NetAction::Raw(s) => vec![s.clone()], // Internal: the link layer handles these before serialization. - NetAction::DeferRegister { .. } | NetAction::DeferPassword { .. } | NetAction::DeferAuthenticate { .. } | NetAction::DeferKeycard { .. } | NetAction::SendEmail { .. } | NetAction::Shutdown { .. } => vec![], + NetAction::DeferRegister { .. } | NetAction::DeferPassword { .. } | NetAction::DeferAuthenticate { .. } | NetAction::DeferKeycard { .. } | NetAction::SendEmail { .. } | NetAction::Shutdown { .. } | NetAction::Rehash { .. } => vec![], }; // A trailing parameter can carry free-form text (message bodies, kick // reasons, topics, metadata). Strip CR/LF/NUL at this single choke-point diff --git a/src/engine/mod.rs b/src/engine/mod.rs index c86d6fb..6a9f645 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -107,6 +107,7 @@ pub struct Engine { service_oper_type: String, // oper type our services are flagged with (WHOIS "is a "); empty = don't oper services_channel: String, // channel all service pseudo-clients join at startup; empty = none standard_replies: bool, // emit IRCv3 FAIL/WARN/NOTE for service errors; off = degrade to notices + config_path: String, // path to config.toml, so OperServ REHASH can re-read it live enforce_seq: u32, // counter appended to guest_nick pending_enforce: Vec, // registered nicks awaiting identify-or-rename bot_uids: HashMap, // casefolded bot nick -> live uid (per connection) @@ -244,6 +245,7 @@ impl Engine { service_oper_type: String::new(), services_channel: String::new(), standard_replies: false, + config_path: String::new(), enforce_seq: 0, pending_enforce: Vec::new(), bot_uids: HashMap::new(), @@ -791,6 +793,54 @@ impl Engine { self.standard_replies = on; } + pub fn set_config_path(&mut self, path: impl Into) { + self.config_path = path.into(); + } + + // Re-read config.toml and apply the settings that are safe to change while + // linked, reporting the outcome to the oper who ran REHASH. A parse error + // keeps the running configuration untouched (validate-or-keep, like an ircd + // rehash). Server identity (name/sid/protocol/uplink), service umodes and the + // keycard endpoint are NOT reloadable — they need a restart. + pub fn rehash(&mut self, requester: &str, agent: &str) -> Vec { + let path = self.config_path.clone(); + let cfg = match crate::config::Config::load(&path) { + Ok(cfg) => cfg, + Err(e) => { + return vec![NetAction::Notice { + from: agent.to_string(), + to: requester.to_string(), + text: format!("REHASH failed: {e}. The running configuration is unchanged."), + }]; + } + }; + let opers = cfg.opers(); + let oper_count = opers.len(); + self.set_opers(opers); + self.set_service_oper_type(cfg.server.service_oper_type.clone()); + self.set_services_channel(cfg.server.services_channel.clone()); + self.set_standard_replies(cfg.server.standard_replies); + self.set_log_channel(cfg.log.as_ref().map(|l| l.channel.clone())); + self.set_guest_nick(&cfg.server.guest_nick); + if let Some(expire) = &cfg.expire { + self.set_expiry(expire.account_ttl(), expire.channel_ttl(), expire.warn_ttl()); + } + if let Some(session) = &cfg.session { + self.set_session_limit(session.limit()); + } + let notice = |text: String| NetAction::Notice { from: agent.to_string(), to: requester.to_string(), text }; + vec![ + notice(format!("Configuration reloaded from \x02{path}\x02.")), + notice(format!( + "Applied: \x02{oper_count}\x02 oper(s), standard-replies \x02{}\x02, services channel \x02{}\x02, service oper-type \x02{}\x02.", + if self.standard_replies { "on" } else { "off" }, + if self.services_channel.is_empty() { "(none)" } else { &self.services_channel }, + if self.service_oper_type.is_empty() { "(none)" } else { &self.service_oper_type }, + )), + notice("Not reloadable (need a RESTART): server name/SID/protocol, uplink, service umodes, keycard.".to_string()), + ] + } + // A user arrived on (or changed to) a registered nick: if they aren't logged // into that account, prompt them to IDENTIFY and schedule a rename. Gated on // `synced` so a netburst can't enforce every already-online user; a user who diff --git a/src/engine/tests.rs b/src/engine/tests.rs index bfbc2b9..b6b5d56 100644 --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -673,6 +673,44 @@ assert_eq!(e.network.account_of("000AAAAAB"), None, "empty account is a logout"); } + // OperServ REHASH is admin-only and hands the reload to the engine (resolved + // in the link layer) addressed back to the oper who ran it. + #[test] + fn operserv_rehash_is_admin_only() { + use echo_operserv::OperServ; + let path = std::env::temp_dir().join("echo-opsrehash.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "test"); + db.scram_iterations = 4096; + db.register("alice", "sesame", None).unwrap(); + db.register("bob", "sesame", None).unwrap(); + let mut e = Engine::new( + vec![ + Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }), + Box::new(OperServ { uid: "42SAAAAAH".into() }), + ], + db, + ); + e.set_sid("42S".into()); + let mut opers = std::collections::HashMap::new(); + opers.insert("alice".to_string(), Privs::default().with(echo_api::Priv::Admin)); + opers.insert("bob".to_string(), Privs::default().with(echo_api::Priv::Auspex)); + e.set_opers(opers); + e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "alice".into(), host: "h".into(), ip: "0.0.0.0".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAA".into(), text: "IDENTIFY sesame".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAC".into(), nick: "bob".into(), host: "h".into(), ip: "0.0.0.0".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAC".into(), to: "42SAAAAAA".into(), text: "IDENTIFY sesame".into() }); + + // Admin: hands off the reload, addressed back to the requesting oper. + let a = e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAH".into(), text: "REHASH".into() }); + assert!(a.iter().any(|x| matches!(x, NetAction::Rehash { requester, agent } if requester == "000AAAAAB" && agent == "42SAAAAAH")), "{a:?}"); + + // Oper without admin: denied, no reload handed off. + let b = e.handle(NetEvent::Privmsg { from: "000AAAAAC".into(), to: "42SAAAAAH".into(), text: "REHASH".into() }); + assert!(!b.iter().any(|x| matches!(x, NetAction::Rehash { .. })), "non-admin must not rehash: {b:?}"); + assert!(b.iter().any(|x| matches!(x, NetAction::Notice { text, .. } if text.contains("admin"))), "{b:?}"); + } + // A login that finishes off the handle() path (the link layer's deferred // password/keycard verify) must still make echo's OWN account map authoritative. // Otherwise re-identifying an already-logged-in user after a services relink — diff --git a/src/link.rs b/src/link.rs index 16e07dc..140ed0a 100644 --- a/src/link.rs +++ b/src/link.rs @@ -143,6 +143,11 @@ pub async fn run(mut proto: Box, engine: Arc>, addr: .await?; engine.lock().await.complete_authenticate(ok, then) } + // OperServ REHASH: re-read config.toml and apply the + // reloadable settings live, reporting back to the oper. + NetAction::Rehash { requester, agent } => { + engine.lock().await.rehash(&requester, &agent) + } action => vec![action], }; for act in outs { diff --git a/src/main.rs b/src/main.rs index 50efab9..69edc1e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -184,6 +184,7 @@ async fn main() -> Result<()> { let (irc_tx, irc_rx) = tokio::sync::mpsc::unbounded_channel(); engine.lock().await.set_irc_out(irc_tx); engine.lock().await.set_opers(cfg.opers()); + engine.lock().await.set_config_path(path.clone()); engine.lock().await.set_sid(cfg.server.sid.clone()); engine.lock().await.set_guest_nick(&cfg.server.guest_nick); // Service pseudo-clients wear the configured host, or the server name.