diff --git a/api/src/lib.rs b/api/src/lib.rs index 6b529e1..be2ae8a 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -111,6 +111,10 @@ pub enum NetAction { // Internal only: send an email (plaintext + optional HTML). The link layer // pipes it to the configured mail command off-thread; never serialized. SendEmail { to: String, subject: String, text: String, html: Option }, + // Internal only: stop the services process (OperServ SHUTDOWN/RESTART). The + // link layer exits cleanly; `restart` exits non-zero so a supervisor (systemd + // Restart=) brings it back. Never serialized. + Shutdown { restart: bool, reason: String }, } // How to answer a registration once its credentials have been derived. @@ -281,6 +285,13 @@ impl ServiceCtx { self.actions.push(NetAction::SendEmail { to: to.into(), subject: subject.into(), text: text.into(), html }); } + // Stop the services process (OperServ SHUTDOWN/RESTART). The link layer exits + // once this action is reached; `restart` exits non-zero so a supervisor + // respawns us. + pub fn shutdown(&mut self, restart: bool, reason: impl Into) { + self.actions.push(NetAction::Shutdown { restart, reason: reason.into() }); + } + // 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 f7f674f..337803b 100644 --- a/modules/operserv/src/lib.rs +++ b/modules/operserv/src/lib.rs @@ -37,6 +37,8 @@ mod chankill; mod logsearch; #[path = "defcon.rs"] mod defcon; +#[path = "shutdown.rs"] +mod shutdown; pub struct OperServ { pub uid: String, @@ -88,6 +90,8 @@ impl Service for OperServ { Some(cmd) if cmd.eq_ignore_ascii_case("CHANKILL") => chankill::handle(me, from, args, ctx, net, db), Some(cmd) if cmd.eq_ignore_ascii_case("LOGSEARCH") => logsearch::handle(me, from, args, ctx, net), Some(cmd) if cmd.eq_ignore_ascii_case("DEFCON") => defcon::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("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.")), @@ -121,4 +125,6 @@ const TOPICS: &[HelpEntry] = &[ HelpEntry { cmd: "JUPE", summary: "jupe a server name", detail: "Syntax: \x02JUPE [reason] | JUPE DEL | JUPE LIST\x02\nBlocks a server name from linking." }, HelpEntry { cmd: "LOGSEARCH", summary: "search the action log", detail: "Syntax: \x02LOGSEARCH [pattern]\x02\nSearches the incident and action log." }, HelpEntry { cmd: "DEFCON", summary: "network defence level", detail: "Syntax: \x02DEFCON [1-5]\x02\nShows or sets the network defence level (5 = normal, 1 = lockdown)." }, + 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)." }, ]; diff --git a/modules/operserv/src/shutdown.rs b/modules/operserv/src/shutdown.rs new file mode 100644 index 0000000..4891c0f --- /dev/null +++ b/modules/operserv/src/shutdown.rs @@ -0,0 +1,19 @@ +use echo_api::{Priv, Sender, ServiceCtx}; + +// SHUTDOWN / RESTART [reason]: stop the services process. `restart` selects +// which — a restart exits so a supervisor respawns us, a shutdown stays down. +// Admin-only, and the heaviest command services have. Announced network-wide +// first so users know why services vanished. +pub fn handle(me: &str, from: &Sender, restart: bool, args: &[&str], ctx: &mut ServiceCtx) { + let cmd = if restart { "RESTART" } else { "SHUTDOWN" }; + if !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, format!("Access denied — {cmd} needs the \x02admin\x02 privilege.")); + return; + } + let reason = if args.len() > 1 { args[1..].join(" ") } else { format!("Services {}", if restart { "restarting" } else { "shutting down" }) }; + let by = from.account.unwrap_or(from.nick); + ctx.global(me, format!("[\x02Network\x02] Services are {} ({reason}).", if restart { "restarting" } else { "going down" })); + ctx.notice(me, from.uid, format!("Services are {}.", if restart { "restarting" } else { "shutting down" })); + // The action is last, so the notices above are flushed before we exit. + ctx.shutdown(restart, format!("{cmd} by {by}: {reason}")); +} diff --git a/modules/protocol/inspircd/src/lib.rs b/modules/protocol/inspircd/src/lib.rs index dc55dbb..732d456 100644 --- a/modules/protocol/inspircd/src/lib.rs +++ b/modules/protocol/inspircd/src/lib.rs @@ -346,7 +346,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::SendEmail { .. } => vec![], + NetAction::DeferRegister { .. } | NetAction::DeferPassword { .. } | NetAction::SendEmail { .. } | NetAction::Shutdown { .. } => 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/tests.rs b/src/engine/tests.rs index 7583a5b..801f2a1 100644 --- a/src/engine/tests.rs +++ b/src/engine/tests.rs @@ -1155,6 +1155,45 @@ assert!(notice(&e.handle(NetEvent::Privmsg { from: "000AAAAAD".into(), to: "42SAAAAAH".into(), text: "FORBID ADD NICK x y".into() }), "Access denied"), "non-oper refused"); } + // OperServ SHUTDOWN/RESTART (admin) emit a Shutdown action (which the link + // layer turns into a process exit) and are refused to non-operators. + #[test] + fn operserv_shutdown_and_restart() { + use echo_nickserv::NickServ; + use echo_operserv::OperServ; + let path = std::env::temp_dir().join("echo-osshutdown.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "42S"); + db.scram_iterations = 4096; + db.register("boss", "pw", 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, + ); + let mut opers = std::collections::HashMap::new(); + opers.insert("boss".to_string(), Privs::default().with(echo_api::Priv::Admin)); + e.set_opers(opers); + e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "boss".into(), host: "h".into(), ip: "0.0.0.0".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAB".into(), to: "42SAAAAAA".into(), text: "IDENTIFY pw".into() }); + let os = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAH".into(), text: t.into() }); + + // A non-oper is refused and no Shutdown action is produced. + e.handle(NetEvent::UserConnect { uid: "000AAAAAD".into(), nick: "rando".into(), host: "h".into(), ip: "0.0.0.0".into() }); + let out = os(&mut e, "000AAAAAD", "SHUTDOWN now"); + assert!(out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Access denied"))), "non-oper refused"); + assert!(!out.iter().any(|a| matches!(a, NetAction::Shutdown { .. })), "no shutdown for non-oper"); + + // The admin's SHUTDOWN emits a Shutdown (restart=false) with the reason. + let out = os(&mut e, "000AAAAAB", "SHUTDOWN maintenance"); + assert!(out.iter().any(|a| matches!(a, NetAction::Shutdown { restart, reason } if !*restart && reason.contains("maintenance"))), "shutdown action: {out:?}"); + // RESTART sets restart=true. + let out = os(&mut e, "000AAAAAB", "RESTART"); + assert!(out.iter().any(|a| matches!(a, NetAction::Shutdown { restart, .. } if *restart)), "restart action: {out:?}"); + } + // OperServ SVSPART (admin) forces a user out of a channel. #[test] fn operserv_svspart() { diff --git a/src/link.rs b/src/link.rs index 28f790c..915ba87 100644 --- a/src/link.rs +++ b/src/link.rs @@ -70,6 +70,10 @@ pub async fn run(mut proto: Box, engine: Arc>, addr: dispatch_email(&email, to, subject, text, html); continue; } + if let NetAction::Shutdown { restart, reason } = act { + let _ = write.flush().await; + shutdown(restart, &reason); + } for out in proto.serialize(&act) { send(&mut write, &out).await?; } @@ -82,6 +86,9 @@ pub async fn run(mut proto: Box, engine: Arc>, addr: Some(action) = irc_rx.recv() => { if let NetAction::SendEmail { to, subject, text, html } = action { dispatch_email(&email, to, subject, text, html); + } else if let NetAction::Shutdown { restart, reason } = action { + let _ = write.flush().await; + shutdown(restart, &reason); } else { for out in proto.serialize(&action) { send(&mut write, &out).await?; @@ -134,6 +141,19 @@ fn dispatch_email(email: &Option, to: String, subject: Str }); } +// Stop the process on an operator's SHUTDOWN/RESTART. Every committed change is +// already fsync'd, so exiting loses nothing. A restart exits non-zero so a +// supervisor configured to restart-on-failure (systemd Restart=on-failure) +// brings us straight back; a plain shutdown exits cleanly and stays down. +fn shutdown(restart: bool, reason: &str) -> ! { + if restart { + tracing::info!(%reason, "operator requested restart, exiting for supervisor to respawn"); + std::process::exit(2); + } + tracing::info!(%reason, "operator requested shutdown, exiting"); + std::process::exit(0); +} + async fn send(write: &mut (impl AsyncWriteExt + Unpin), line: &str) -> Result<()> { tracing::debug!(dir = ">>", %line); write.write_all(line.as_bytes()).await?;