diff --git a/api/src/lib.rs b/api/src/lib.rs index 6d69226..109ea5e 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -345,6 +345,7 @@ pub struct ChannelView { pub secureops: bool, pub keeptopic: bool, pub topiclock: bool, + pub suspended: bool, // Last known topic (for KEEPTOPIC / TOPICLOCK). pub topic: String, } @@ -491,6 +492,10 @@ pub trait Store { fn set_desc(&mut self, channel: &str, desc: &str) -> Result<(), ChanError>; fn set_channel_setting(&mut self, channel: &str, setting: ChanSetting, on: bool) -> Result<(), ChanError>; fn set_channel_topic(&mut self, channel: &str, topic: &str) -> Result<(), ChanError>; + fn suspend_channel(&mut self, channel: &str, by: &str, reason: &str, expires: Option) -> Result<(), ChanError>; + fn unsuspend_channel(&mut self, channel: &str) -> Result; + fn is_channel_suspended(&self, channel: &str) -> bool; + fn channel_suspension(&self, channel: &str) -> Option; fn set_entrymsg(&mut self, channel: &str, msg: &str) -> Result<(), ChanError>; fn set_founder(&mut self, channel: &str, account: &str) -> Result<(), ChanError>; fn access_add(&mut self, channel: &str, account: &str, level: &str) -> Result<(), ChanError>; @@ -535,6 +540,20 @@ pub trait Service: Send { fn on_command(&mut self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView, store: &mut dyn Store); } +// Parse a duration like "30d", "12h", "45m", "90s", or bare seconds. Shared by +// the SUSPEND commands. +pub fn parse_duration(s: &str) -> Option { + let (num, mult) = match s.chars().last()? { + 'd' | 'D' => (&s[..s.len() - 1], 86_400), + 'h' | 'H' => (&s[..s.len() - 1], 3_600), + 'm' | 'M' => (&s[..s.len() - 1], 60), + 's' | 'S' => (&s[..s.len() - 1], 1), + c if c.is_ascii_digit() => (s, 1), + _ => return None, + }; + num.parse::().ok().map(|n| n * mult) +} + // Case-insensitive hostmask glob: `*` (any run) and `?` (one char). fn glob_match(pattern: &str, text: &str) -> bool { let (p, t): (Vec, Vec) = ( diff --git a/chanserv/src/lib.rs b/chanserv/src/lib.rs index 1d6edbd..125853e 100644 --- a/chanserv/src/lib.rs +++ b/chanserv/src/lib.rs @@ -38,6 +38,8 @@ mod enforce; mod clone; #[path = "xop.rs"] mod xop; +#[path = "suspend.rs"] +mod suspend; pub struct ChanServ { pub uid: String, @@ -101,6 +103,9 @@ impl Service for ChanServ { ctx.notice(me, from.uid, format!(" Description: {}", info.desc)); } ctx.notice(me, from.uid, format!(" Registered : {}", fedserv_api::human_time(info.ts))); + if let Some(s) = db.channel_suspension(chan) { + ctx.notice(me, from.uid, format!(" Suspended : by \x02{}\x02 — {}", s.by, s.reason)); + } let mut opts = Vec::new(); if info.signkick { opts.push("SIGNKICK"); } if info.private { opts.push("PRIVATE"); } @@ -132,6 +137,9 @@ impl Service for ChanServ { ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can drop it.")); return; } + if suspended_block(me, from, chan, ctx, db) { + return; + } match db.drop_channel(chan) { Ok(()) => { ctx.channel_mode(me, chan, "-r"); // no longer registered @@ -168,6 +176,9 @@ impl Service for ChanServ { ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can set its mode lock.")); return; } + if suspended_block(me, from, chan, ctx, db) { + return; + } let (on, off) = parse_mlock(&args[2..].concat()); match db.set_mlock(chan, &on, &off) { Ok(()) => { @@ -192,6 +203,8 @@ impl Service for ChanServ { Some("INVITE") => invite::handle(me, from, args, ctx, net, db), Some("AKICK") => akick::handle(me, from, args, ctx, db), Some("STATUS") => status::handle(me, from, args, ctx, net, db), + Some("SUSPEND") => suspend::handle(me, from, args, ctx, net, db, true), + Some("UNSUSPEND") => suspend::handle(me, from, args, ctx, net, db, false), Some("LIST") => list::handle(me, from, args, ctx, db), Some("SET") => set::handle(me, from, args, ctx, db), Some("ENTRYMSG") => entrymsg::handle(me, from, args, ctx, db), @@ -211,6 +224,9 @@ impl Service for ChanServ { // True if `from` is the channel's founder; otherwise notices why and returns false. fn require_founder(me: &str, from: &Sender, chan: &str, ctx: &mut ServiceCtx, db: &dyn Store) -> bool { + if suspended_block(me, from, chan, ctx, db) { + return false; + } match db.channel(chan) { None => { ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered.")); @@ -226,6 +242,9 @@ fn require_founder(me: &str, from: &Sender, chan: &str, ctx: &mut ServiceCtx, db // True if `from` is the founder or an access-list op of `chan`; else notices why. fn require_op(me: &str, from: &Sender, chan: &str, ctx: &mut ServiceCtx, db: &dyn Store) -> bool { + if suspended_block(me, from, chan, ctx, db) { + return false; + } match (from.account, db.channel(chan)) { (_, None) => { ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered.")); @@ -239,6 +258,15 @@ fn require_op(me: &str, from: &Sender, chan: &str, ctx: &mut ServiceCtx, db: &dy } } +// A suspended channel is frozen: ChanServ won't manage it (returns true + notices). +fn suspended_block(me: &str, from: &Sender, chan: &str, ctx: &mut ServiceCtx, db: &dyn Store) -> bool { + if db.is_channel_suspended(chan) { + ctx.notice(me, from.uid, format!("\x02{chan}\x02 is suspended by network staff and can't be managed right now.")); + return true; + } + false +} + // PEACE: returns true (and notices) if `from` may not act against `target_uid` // because the channel has PEACE set and the target holds equal-or-higher access. fn peace_blocks(me: &str, from: &Sender, chan: &str, target_uid: &str, ctx: &mut ServiceCtx, net: &dyn NetView, db: &dyn Store) -> bool { diff --git a/chanserv/src/set.rs b/chanserv/src/set.rs index 7d2d2c8..0fac711 100644 --- a/chanserv/src/set.rs +++ b/chanserv/src/set.rs @@ -17,6 +17,9 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can change its settings.")); return; } + if super::suspended_block(me, from, chan, ctx, db) { + return; + } match args.get(2).map(|s| s.to_ascii_uppercase()).as_deref() { Some("FOUNDER") => { let Some(&account) = args.get(3) else { diff --git a/chanserv/src/suspend.rs b/chanserv/src/suspend.rs new file mode 100644 index 0000000..37b2f51 --- /dev/null +++ b/chanserv/src/suspend.rs @@ -0,0 +1,53 @@ +use fedserv_api::{parse_duration, NetView, Priv, Sender, ServiceCtx, Store}; +use std::time::{SystemTime, UNIX_EPOCH}; + +// SUSPEND <#channel> [+expiry] [reason] / UNSUSPEND <#channel>: freeze or unfreeze +// a channel. Its data is kept but it can't be managed while suspended. Oper-only +// (Priv::Suspend). `suspending` selects SUSPEND vs UNSUSPEND. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView, db: &mut dyn Store, suspending: bool) { + if !from.privs.has(Priv::Suspend) { + ctx.notice(me, from.uid, "Access denied — that command is for services operators."); + return; + } + let Some(&chan) = args.get(1) else { + let syntax = if suspending { "Syntax: SUSPEND <#channel> [+expiry] [reason]" } else { "Syntax: UNSUSPEND <#channel>" }; + ctx.notice(me, from.uid, syntax); + return; + }; + if db.channel(chan).is_none() { + ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered.")); + return; + } + + if !suspending { + match db.unsuspend_channel(chan) { + Ok(true) => ctx.notice(me, from.uid, format!("\x02{chan}\x02 is no longer suspended.")), + Ok(false) => ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't suspended.")), + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } + return; + } + + let mut rest = &args[2..]; + let expires = rest.first().and_then(|t| t.strip_prefix('+')).and_then(parse_duration).map(|secs| now_unix() + secs); + if expires.is_some() { + rest = &rest[1..]; + } + let reason = if rest.is_empty() { "This channel has been suspended.".to_string() } else { rest.join(" ") }; + let by = from.account.unwrap_or(from.nick); + match db.suspend_channel(chan, by, &reason, expires) { + Ok(()) => { + // Clear the channel: kick everyone currently in it. + for uid in net.channel_members(chan) { + ctx.kick(me, chan, &uid, &reason); + } + let expiry = if expires.is_some() { " (with expiry)" } else { "" }; + ctx.notice(me, from.uid, format!("\x02{chan}\x02 is now suspended{expiry}.")); + } + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } +} + +fn now_unix() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} diff --git a/nickserv/src/suspend.rs b/nickserv/src/suspend.rs index 21ddc88..bb1acfe 100644 --- a/nickserv/src/suspend.rs +++ b/nickserv/src/suspend.rs @@ -1,4 +1,4 @@ -use fedserv_api::{NetView, Priv, Sender, ServiceCtx, Store}; +use fedserv_api::{parse_duration, NetView, Priv, Sender, ServiceCtx, Store}; use std::time::{SystemTime, UNIX_EPOCH}; // SUSPEND [+expiry] [reason] / UNSUSPEND : freeze or unfreeze @@ -49,19 +49,6 @@ pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: } } -// Parse a duration like "30d", "12h", "45m", "90s", or a bare number of seconds. -fn parse_duration(s: &str) -> Option { - let (num, mult) = match s.chars().last()? { - 'd' | 'D' => (&s[..s.len() - 1], 86_400), - 'h' | 'H' => (&s[..s.len() - 1], 3_600), - 'm' | 'M' => (&s[..s.len() - 1], 60), - 's' | 'S' => (&s[..s.len() - 1], 1), - c if c.is_ascii_digit() => (s, 1), - _ => return None, - }; - num.parse::().ok().map(|n| n * mult) -} - fn now_unix() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) } diff --git a/src/engine/db.rs b/src/engine/db.rs index 30b2677..d2dde66 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -89,6 +89,8 @@ pub enum Event { ChannelEntryMsgSet { channel: String, msg: String }, ChannelSettingsSet { channel: String, settings: ChanSettings }, ChannelTopicSet { channel: String, topic: String }, + ChannelSuspended { channel: String, by: String, reason: String, ts: u64, expires: Option }, + ChannelUnsuspended { channel: String }, } // Whether an event replicates across the federation. Account identity is Global @@ -128,7 +130,9 @@ impl Event { | Event::ChannelDescSet { .. } | Event::ChannelEntryMsgSet { .. } | Event::ChannelSettingsSet { .. } - | Event::ChannelTopicSet { .. } => Scope::Local, + | Event::ChannelTopicSet { .. } + | Event::ChannelSuspended { .. } + | Event::ChannelUnsuspended { .. } => Scope::Local, } } } @@ -218,6 +222,9 @@ pub struct ChannelInfo { // Last known topic, kept for KEEPTOPIC / TOPICLOCK. #[serde(default)] pub topic: String, + // Services suspension, if any (channel frozen while set and unexpired). + #[serde(default)] + pub suspension: Option, } impl ChannelInfo { @@ -627,6 +634,9 @@ impl Db { if !c.topic.is_empty() { snapshot.push(Event::ChannelTopicSet { channel: c.name.clone(), topic: c.topic.clone() }); } + if let Some(s) = &c.suspension { + snapshot.push(Event::ChannelSuspended { channel: c.name.clone(), by: s.by.clone(), reason: s.reason.clone(), ts: s.ts, expires: s.expires }); + } } for (nick, account) in &self.grouped { snapshot.push(Event::NickGrouped { nick: nick.clone(), account: account.clone() }); @@ -1053,7 +1063,7 @@ impl Db { self.log .append(Event::ChannelRegistered { name: name.to_string(), founder: founder.to_string(), ts }) .map_err(|_| ChanError::Internal)?; - self.channels.insert(k, ChannelInfo { name: name.to_string(), founder: founder.to_string(), ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new() }); + self.channels.insert(k, ChannelInfo { name: name.to_string(), founder: founder.to_string(), ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new(), suspension: None }); Ok(()) } @@ -1222,6 +1232,41 @@ impl Db { Ok(()) } + /// Suspend a channel. `expires` is absolute unix time (None = permanent). + pub fn suspend_channel(&mut self, channel: &str, by: &str, reason: &str, expires: Option) -> Result<(), ChanError> { + let k = key(channel); + if !self.channels.contains_key(&k) { + return Err(ChanError::NoChannel); + } + let ts = now(); + self.log.append(Event::ChannelSuspended { channel: channel.to_string(), by: by.to_string(), reason: reason.to_string(), ts, expires }).map_err(|_| ChanError::Internal)?; + self.channels.get_mut(&k).unwrap().suspension = Some(Suspension { by: by.to_string(), reason: reason.to_string(), ts, expires }); + Ok(()) + } + + /// Lift a channel suspension. Returns whether one was set. + pub fn unsuspend_channel(&mut self, channel: &str) -> Result { + let k = key(channel); + match self.channels.get(&k) { + None => return Err(ChanError::NoChannel), + Some(c) if c.suspension.is_none() => return Ok(false), + Some(_) => {} + } + self.log.append(Event::ChannelUnsuspended { channel: channel.to_string() }).map_err(|_| ChanError::Internal)?; + self.channels.get_mut(&k).unwrap().suspension = None; + Ok(true) + } + + /// Whether a channel has a set, unexpired suspension (lazy — no timer). + pub fn is_channel_suspended(&self, channel: &str) -> bool { + self.channels.get(&key(channel)).and_then(|c| c.suspension.as_ref()).is_some_and(|s| s.expires.is_none_or(|e| e > now())) + } + + /// The channel's suspension record, if any. + pub fn channel_suspension(&self, channel: &str) -> Option { + self.channels.get(&key(channel)).and_then(|c| c.suspension.as_ref()).map(|s| SuspensionView { by: s.by.clone(), reason: s.reason.clone(), ts: s.ts, expires: s.expires }) + } + /// Set `channel`'s entry message (empty clears it). pub fn set_entrymsg(&mut self, channel: &str, msg: &str) -> Result<(), ChanError> { let k = key(channel); @@ -1333,7 +1378,7 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { - channels.insert(key(&name), ChannelInfo { name, founder, ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new() }); + channels.insert(key(&name), ChannelInfo { name, founder, ts, lock_on: String::new(), lock_off: String::new(), access: Vec::new(), akick: Vec::new(), desc: String::new(), entrymsg: String::new(), settings: ChanSettings::default(), topic: String::new(), suspension: None }); } Event::ChannelDropped { name } => { channels.remove(&key(&name)); @@ -1386,6 +1431,16 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { + if let Some(c) = channels.get_mut(&key(&channel)) { + c.suspension = Some(Suspension { by, reason, ts, expires }); + } + } + Event::ChannelUnsuspended { channel } => { + if let Some(c) = channels.get_mut(&key(&channel)) { + c.suspension = None; + } + } Event::ChannelEntryMsgSet { channel, msg } => { if let Some(c) = channels.get_mut(&key(&channel)) { c.entrymsg = msg; @@ -1575,6 +1630,18 @@ impl Store for Db { fn set_channel_topic(&mut self, channel: &str, topic: &str) -> Result<(), ChanError> { Db::set_channel_topic(self, channel, topic) } + fn suspend_channel(&mut self, channel: &str, by: &str, reason: &str, expires: Option) -> Result<(), ChanError> { + Db::suspend_channel(self, channel, by, reason, expires) + } + fn unsuspend_channel(&mut self, channel: &str) -> Result { + Db::unsuspend_channel(self, channel) + } + fn is_channel_suspended(&self, channel: &str) -> bool { + Db::is_channel_suspended(self, channel) + } + fn channel_suspension(&self, channel: &str) -> Option { + Db::channel_suspension(self, channel) + } fn set_entrymsg(&mut self, channel: &str, msg: &str) -> Result<(), ChanError> { Db::set_entrymsg(self, channel, msg) } @@ -1613,6 +1680,7 @@ fn channel_view(c: &ChannelInfo) -> ChannelView { keeptopic: c.settings.keeptopic, topiclock: c.settings.topiclock, topic: c.topic.clone(), + suspended: c.suspension.as_ref().is_some_and(|s| s.expires.is_none_or(|e| e > now())), } } @@ -1789,6 +1857,23 @@ mod tests { assert!(Db::open(&p, "N1").is_suspended("alice"), "suspension replays from the log"); } + // A channel suspension lifts, expires lazily, and survives compaction + reopen. + #[test] + fn channel_suspend_lifts_persists_and_compacts() { + let p = tmp("chansuspend"); + let mut db = Db::open(&p, "N1"); + db.register_channel("#c", "boss").unwrap(); + db.suspend_channel("#c", "oper", "raided", Some(1)).unwrap(); + assert!(!db.is_channel_suspended("#c"), "a past expiry is inactive"); + db.suspend_channel("#c", "oper", "raided", None).unwrap(); + assert!(db.is_channel_suspended("#c")); + db.compact().unwrap(); // the snapshot must retain the suspension + drop(db); + let db = Db::open(&p, "N1"); + assert!(db.is_channel_suspended("#c"), "survives compaction + reopen"); + assert_eq!(db.channel_suspension("#c").unwrap().by, "oper"); + } + // A wrong code is tolerated a few times, then the code is burned so it can't // be ground down online even though it is short. #[test] diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 2f652f2..ac6e9c7 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -449,6 +449,10 @@ impl Engine { // members their status mode, and send the entry message. NetEvent::Join { uid, channel, op } => { self.network.channel_join(&channel, &uid, op); + // A suspended channel is frozen: no auto-op, akick, or entry message. + if self.db.is_channel_suspended(&channel) { + return Vec::new(); + } let account = self.network.account_of(&uid).map(str::to_string); let from = self.chan_service.clone().unwrap_or_default(); let mode = account.as_deref().and_then(|a| self.db.channel(&channel).and_then(|c| c.join_mode(a))); @@ -1553,6 +1557,48 @@ mod tests { assert!(out.is_empty(), "no enforcement when SECUREOPS is off: {out:?}"); } + // Channel SUSPEND is oper-gated and freezes founder management until lifted. + #[test] + fn channel_suspend_is_oper_gated_and_freezes_management() { + use fedserv_chanserv::ChanServ; + use fedserv_nickserv::NickServ; + let path = std::env::temp_dir().join("fedserv-chansuspendcmd.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "42S"); + db.scram_iterations = 4096; + db.register("boss", "password1", None).unwrap(); + db.register("staff", "password1", None).unwrap(); + db.register_channel("#c", "boss").unwrap(); + let mut e = Engine::new( + vec![ + Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }), + Box::new(ChanServ { uid: "42SAAAAAB".into() }), + ], + db, + ); + let mut opers = std::collections::HashMap::new(); + opers.insert("staff".to_string(), Privs::default().with(fedserv_api::Priv::Suspend)); + e.set_opers(opers); + let ns = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAA".into(), text: t.into() }); + let cs = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAB".into(), text: t.into() }); + let notice = |out: &[NetAction], n: &str| out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains(n))); + + e.handle(NetEvent::UserConnect { uid: "000AAAAAB".into(), nick: "boss".into(), host: "h".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAC".into(), nick: "staff".into(), host: "h".into() }); + ns(&mut e, "000AAAAAB", "IDENTIFY password1"); + ns(&mut e, "000AAAAAC", "IDENTIFY password1"); + + // A non-oper cannot suspend a channel. + assert!(notice(&cs(&mut e, "000AAAAAB", "SUSPEND #c"), "Access denied")); + // The oper suspends it. + assert!(notice(&cs(&mut e, "000AAAAAC", "SUSPEND #c raided"), "now suspended")); + // The founder can no longer manage it. + assert!(notice(&cs(&mut e, "000AAAAAB", "SET #c SIGNKICK ON"), "suspended")); + // UNSUSPEND restores management. + assert!(notice(&cs(&mut e, "000AAAAAC", "UNSUSPEND #c"), "no longer suspended")); + assert!(notice(&cs(&mut e, "000AAAAAB", "SET #c SIGNKICK ON"), "is now")); + } + // SUSPEND is oper-gated, blocks the victim's login, and UNSUSPEND restores it. #[test] fn suspend_blocks_login_and_needs_oper() { diff --git a/src/grpc.rs b/src/grpc.rs index 323aa88..64e6ab6 100644 --- a/src/grpc.rs +++ b/src/grpc.rs @@ -133,7 +133,9 @@ fn to_wire(entry: &LogEntry) -> Option { | Event::ChannelAkickDel { .. } | Event::ChannelEntryMsgSet { .. } | Event::ChannelSettingsSet { .. } - | Event::ChannelTopicSet { .. } => return None, + | Event::ChannelTopicSet { .. } + | Event::ChannelSuspended { .. } + | Event::ChannelUnsuspended { .. } => return None, }; Some(ReplicationEvent { origin: entry.origin().to_string(), seq: entry.seq(), lamport: entry.lamport(), kind: Some(kind) }) }