Reorganize protocol and pseudoclients into a modules/ tree
The core stays in src/; protocol and pseudoclients move to modules/, pulled in with #[path].
This commit is contained in:
parent
dbc45a0b6a
commit
677963924a
11 changed files with 43 additions and 17 deletions
19
modules/README.md
Normal file
19
modules/README.md
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
# modules/
|
||||
|
||||
The pluggable parts of fedserv: one directory per protocol and per pseudoclient.
|
||||
The core (engine, event log, gossip, link loop) stays in `../src/`.
|
||||
|
||||
```
|
||||
modules/
|
||||
protocol/ ircd link protocols (inspircd.rs)
|
||||
nickserv/ NickServ pseudoclient
|
||||
chanserv/ ChanServ pseudoclient
|
||||
```
|
||||
|
||||
`src/main.rs` pulls each in with `#[path = "../modules/..."]`, so crate paths
|
||||
stay flat (`crate::proto`, `crate::nickserv`, `crate::chanserv`).
|
||||
|
||||
## Naming
|
||||
|
||||
A service directory holds its pseudoclient file plus, as commands are split out,
|
||||
one file per command with the service prefix: `ns_register.rs`, `cs_mode.rs`, etc.
|
||||
224
modules/chanserv/chanserv.rs
Normal file
224
modules/chanserv/chanserv.rs
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
use crate::engine::db::{ChanError, ChannelInfo, Db};
|
||||
use crate::engine::service::{Sender, Service, ServiceCtx};
|
||||
|
||||
pub struct ChanServ {
|
||||
pub uid: String,
|
||||
}
|
||||
|
||||
impl Service for ChanServ {
|
||||
fn nick(&self) -> &str {
|
||||
"ChanServ"
|
||||
}
|
||||
fn uid(&self) -> &str {
|
||||
&self.uid
|
||||
}
|
||||
fn gecos(&self) -> &str {
|
||||
"Channel Services"
|
||||
}
|
||||
fn manages_channels(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn on_command(&mut self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut Db) {
|
||||
let me = self.uid.as_str();
|
||||
match args.first().map(|s| s.to_ascii_uppercase()).as_deref() {
|
||||
Some("REGISTER") => {
|
||||
let Some(&chan) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: REGISTER <#channel>");
|
||||
return;
|
||||
};
|
||||
if !chan.starts_with('#') {
|
||||
ctx.notice(me, from.uid, "Channel names start with \x02#\x02.");
|
||||
return;
|
||||
}
|
||||
// The founder is the account the sender is identified to.
|
||||
let Some(account) = from.account else {
|
||||
ctx.notice(me, from.uid, "You need to be logged in to register a channel. Identify to NickServ first.");
|
||||
return;
|
||||
};
|
||||
match db.register_channel(chan, account) {
|
||||
Ok(()) => {
|
||||
ctx.channel_mode(me, chan, "+r"); // mark the channel registered
|
||||
ctx.notice(me, from.uid, format!("\x02{chan}\x02 is now registered and you are its founder. Enjoy!"));
|
||||
}
|
||||
Err(ChanError::Exists) => ctx.notice(me, from.uid, format!("\x02{chan}\x02 is already registered. Try \x02INFO {chan}\x02 to see who owns it.")),
|
||||
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||
}
|
||||
}
|
||||
Some("INFO") => {
|
||||
let Some(&chan) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: INFO <#channel>");
|
||||
return;
|
||||
};
|
||||
match db.channel(chan) {
|
||||
Some(info) => {
|
||||
ctx.notice(me, from.uid, format!("Information for \x02{}\x02:", info.name));
|
||||
ctx.notice(me, from.uid, format!(" Founder : \x02{}\x02", info.founder));
|
||||
ctx.notice(me, from.uid, format!(" Registered : {}", human_time(info.ts)));
|
||||
}
|
||||
None => ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered.")),
|
||||
}
|
||||
}
|
||||
Some("DROP") => {
|
||||
let Some(&chan) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: DROP <#channel>");
|
||||
return;
|
||||
};
|
||||
// Read the founder, then drop, without holding the borrow across the mutation.
|
||||
let founder = match db.channel(chan) {
|
||||
Some(info) => info.founder.clone(),
|
||||
None => {
|
||||
ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered."));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if from.account != Some(founder.as_str()) {
|
||||
ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can drop it."));
|
||||
return;
|
||||
}
|
||||
match db.drop_channel(chan) {
|
||||
Ok(()) => {
|
||||
ctx.channel_mode(me, chan, "-r"); // no longer registered
|
||||
ctx.notice(me, from.uid, format!("\x02{chan}\x02 has been dropped and is no longer registered."));
|
||||
}
|
||||
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||
}
|
||||
}
|
||||
Some("MLOCK") => {
|
||||
let Some(&chan) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: MLOCK <#channel> [modes], e.g. MLOCK #chan +nt-s");
|
||||
return;
|
||||
};
|
||||
// No modes given: show the current lock.
|
||||
if args.len() <= 2 {
|
||||
match db.channel(chan) {
|
||||
None => ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered.")),
|
||||
Some(info) if info.lock_on.is_empty() && info.lock_off.is_empty() => {
|
||||
ctx.notice(me, from.uid, format!("\x02{}\x02 has no mode lock set.", info.name));
|
||||
}
|
||||
Some(info) => ctx.notice(me, from.uid, format!("Mode lock for \x02{}\x02: \x02{}\x02", info.name, show_mlock(info))),
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Setting the lock: founder only.
|
||||
let founder = match db.channel(chan) {
|
||||
Some(info) => info.founder.clone(),
|
||||
None => {
|
||||
ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered."));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if from.account != Some(founder.as_str()) {
|
||||
ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can set its mode lock."));
|
||||
return;
|
||||
}
|
||||
let (on, off) = parse_mlock(&args[2..].concat());
|
||||
match db.set_mlock(chan, &on, &off) {
|
||||
Ok(()) => {
|
||||
if let Some(info) = db.channel(chan) {
|
||||
ctx.channel_mode(me, chan, &info.lock_modes()); // apply it now
|
||||
}
|
||||
ctx.notice(me, from.uid, format!("Mode lock for \x02{chan}\x02 updated."));
|
||||
}
|
||||
Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."),
|
||||
}
|
||||
}
|
||||
Some("MODE") => {
|
||||
let Some(&chan) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: MODE <#channel> <modes>, e.g. MODE #chan +nt");
|
||||
return;
|
||||
};
|
||||
if args.len() <= 2 {
|
||||
ctx.notice(me, from.uid, "Syntax: MODE <#channel> <modes>, e.g. MODE #chan +nt");
|
||||
return;
|
||||
}
|
||||
let founder = match db.channel(chan) {
|
||||
Some(info) => info.founder.clone(),
|
||||
None => {
|
||||
ctx.notice(me, from.uid, format!("\x02{chan}\x02 isn't registered."));
|
||||
return;
|
||||
}
|
||||
};
|
||||
if from.account != Some(founder.as_str()) {
|
||||
ctx.notice(me, from.uid, format!("Only \x02{chan}\x02's founder can change its modes."));
|
||||
return;
|
||||
}
|
||||
let modes = args[2..].join(" ");
|
||||
ctx.channel_mode(me, chan, &modes);
|
||||
ctx.notice(me, from.uid, format!("Set \x02{modes}\x02 on \x02{chan}\x02."));
|
||||
}
|
||||
Some("HELP") => ctx.notice(me, from.uid, "ChanServ registers and looks after channels. Commands: \x02REGISTER\x02 <#channel>, \x02INFO\x02 <#channel>, \x02MODE\x02 <#channel> <modes>, \x02MLOCK\x02 <#channel> [modes], \x02DROP\x02 <#channel>."),
|
||||
Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Parse a mode spec like "+nt-s" into (locked-on, locked-off) mode chars. `r` is
|
||||
// implicit for a registered channel and is ignored here.
|
||||
fn parse_mlock(spec: &str) -> (String, String) {
|
||||
let (mut on, mut off) = (String::new(), String::new());
|
||||
let mut adding = true;
|
||||
for ch in spec.chars() {
|
||||
match ch {
|
||||
'+' => adding = true,
|
||||
'-' => adding = false,
|
||||
'r' => {}
|
||||
m if m.is_ascii_alphabetic() => {
|
||||
on.retain(|c| c != m);
|
||||
off.retain(|c| c != m);
|
||||
if adding {
|
||||
on.push(m);
|
||||
} else {
|
||||
off.push(m);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(on, off)
|
||||
}
|
||||
|
||||
// Render a channel's lock as "+on-off" for display.
|
||||
fn show_mlock(info: &ChannelInfo) -> String {
|
||||
let mut s = String::new();
|
||||
if !info.lock_on.is_empty() {
|
||||
s.push('+');
|
||||
s.push_str(&info.lock_on);
|
||||
}
|
||||
if !info.lock_off.is_empty() {
|
||||
s.push('-');
|
||||
s.push_str(&info.lock_off);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
// Format a Unix timestamp (seconds) as "YYYY-MM-DD HH:MM:SS UTC", using Howard
|
||||
// Hinnant's civil-from-days algorithm so no date crate is needed.
|
||||
fn human_time(ts: u64) -> String {
|
||||
let days = (ts / 86400) as i64;
|
||||
let rem = ts % 86400;
|
||||
let (hh, mm, ss) = (rem / 3600, (rem % 3600) / 60, rem % 60);
|
||||
let z = days + 719468;
|
||||
let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
|
||||
let doe = z - era * 146097;
|
||||
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
|
||||
let y = yoe + era * 400;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = y + i64::from(month <= 2);
|
||||
format!("{year:04}-{month:02}-{day:02} {hh:02}:{mm:02}:{ss:02} UTC")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::human_time;
|
||||
|
||||
#[test]
|
||||
fn formats_unix_time_as_utc() {
|
||||
assert_eq!(human_time(0), "1970-01-01 00:00:00 UTC");
|
||||
assert_eq!(human_time(1783844590), "2026-07-12 08:23:10 UTC");
|
||||
}
|
||||
}
|
||||
144
modules/nickserv/nickserv.rs
Normal file
144
modules/nickserv/nickserv.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
use crate::engine::db::{CertError, Db};
|
||||
use crate::engine::service::{Sender, Service, ServiceCtx};
|
||||
use crate::proto::RegReply;
|
||||
|
||||
pub struct NickServ {
|
||||
pub uid: String,
|
||||
// Nick prefix assigned on LOGOUT (default "Guest"); a per-session sequence is
|
||||
// appended so successive guests don't collide within a run.
|
||||
pub guest_nick: String,
|
||||
pub guest_seq: u32,
|
||||
}
|
||||
|
||||
impl Service for NickServ {
|
||||
fn nick(&self) -> &str {
|
||||
"NickServ"
|
||||
}
|
||||
fn uid(&self) -> &str {
|
||||
&self.uid
|
||||
}
|
||||
fn gecos(&self) -> &str {
|
||||
"Nickname Services"
|
||||
}
|
||||
|
||||
fn on_command(&mut self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut Db) {
|
||||
let me = self.uid.as_str();
|
||||
match args.first().map(|s| s.to_ascii_uppercase()).as_deref() {
|
||||
Some("REGISTER") => {
|
||||
// REGISTER <password> [email] — registers the sender's current nick.
|
||||
let Some(password) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: REGISTER <password> [email]");
|
||||
return;
|
||||
};
|
||||
let email = args.get(2).map(|s| s.to_string());
|
||||
// The engine derives the password off-thread, commits, and answers.
|
||||
ctx.defer_register(from.nick, *password, email, RegReply::NickServ {
|
||||
agent: me.to_string(),
|
||||
uid: from.uid.to_string(),
|
||||
nick: from.nick.to_string(),
|
||||
});
|
||||
}
|
||||
Some("IDENTIFY") => {
|
||||
let Some(password) = args.get(1) else {
|
||||
ctx.notice(me, from.uid, "Syntax: IDENTIFY <password>");
|
||||
return;
|
||||
};
|
||||
match db.authenticate(from.nick, password) {
|
||||
Some(account) => {
|
||||
// Already identified to this account: don't re-fire the login.
|
||||
if from.account == Some(account) {
|
||||
ctx.notice(me, from.uid, format!("You're already identified as \x02{}\x02.", account));
|
||||
return;
|
||||
}
|
||||
let account = account.to_string();
|
||||
ctx.login(from.uid, &account);
|
||||
ctx.notice(me, from.uid, format!("You're now identified as \x02{}\x02. Welcome back!", account));
|
||||
}
|
||||
None => ctx.notice(me, from.uid, "Invalid password. Please try again."),
|
||||
}
|
||||
}
|
||||
Some("LOGOUT") | Some("LOGOFF") => {
|
||||
if from.account.is_none() {
|
||||
ctx.notice(me, from.uid, "You're not logged in.");
|
||||
return;
|
||||
}
|
||||
// Guest nick = prefix + sequence (seeded from the link TS, bumped
|
||||
// per logout). Inlined field access so it stays disjoint from `me`.
|
||||
let guest = format!("{}{}", self.guest_nick, self.guest_seq);
|
||||
self.guest_seq = self.guest_seq.wrapping_add(1);
|
||||
ctx.logout(from.uid);
|
||||
ctx.force_nick(from.uid, &guest);
|
||||
ctx.notice(me, from.uid, format!("You're now logged out. Your nick is now \x02{}\x02.", guest));
|
||||
}
|
||||
Some("CERT") => self.cert(from, &args, ctx, db),
|
||||
Some("HELP") => ctx.notice(
|
||||
me,
|
||||
from.uid,
|
||||
"NickServ looks after your nickname. Commands: \x02REGISTER\x02 <password> [email], \x02IDENTIFY\x02 <password>, \x02LOGOUT\x02, \x02CERT\x02 ADD|DEL|LIST <password> [fingerprint].",
|
||||
),
|
||||
Some(other) => ctx.notice(me, from.uid, format!("I don't know the command \x02{other}\x02. Try \x02HELP\x02.")),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NickServ {
|
||||
// CERT ADD|DEL|LIST <password> [fingerprint]: manage the TLS certificate
|
||||
// fingerprints that may log in to your account via SASL EXTERNAL. Gated by
|
||||
// the account password, so it needs no separate identified-session state.
|
||||
fn cert(&self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut Db) {
|
||||
let me = self.uid.as_str();
|
||||
// All subcommands authenticate the sender's nick's account by password.
|
||||
let auth = |db: &Db, password: &str| db.authenticate(from.nick, password).map(str::to_string);
|
||||
match args.get(1).map(|s| s.to_ascii_uppercase()).as_deref() {
|
||||
Some("LIST") => {
|
||||
let Some(password) = args.get(2) else {
|
||||
ctx.notice(me, from.uid, "Syntax: CERT LIST <password>");
|
||||
return;
|
||||
};
|
||||
let Some(account) = auth(db, password) else {
|
||||
ctx.notice(me, from.uid, "Invalid password.");
|
||||
return;
|
||||
};
|
||||
let fps = db.certfps(&account);
|
||||
if fps.is_empty() {
|
||||
ctx.notice(me, from.uid, "No certificate fingerprints are registered to your account.");
|
||||
} else {
|
||||
ctx.notice(me, from.uid, format!("Registered fingerprints: {}", fps.join(", ")));
|
||||
}
|
||||
}
|
||||
Some("ADD") => {
|
||||
let (Some(password), Some(fp)) = (args.get(2), args.get(3)) else {
|
||||
ctx.notice(me, from.uid, "Syntax: CERT ADD <password> <fingerprint>");
|
||||
return;
|
||||
};
|
||||
let Some(account) = auth(db, password) else {
|
||||
ctx.notice(me, from.uid, "Invalid password.");
|
||||
return;
|
||||
};
|
||||
match db.certfp_add(&account, fp) {
|
||||
Ok(()) => ctx.notice(me, from.uid, format!("Added fingerprint \x02{fp}\x02. You can now log in with SASL EXTERNAL.")),
|
||||
Err(CertError::InUse) => ctx.notice(me, from.uid, "That fingerprint is already registered."),
|
||||
Err(CertError::Invalid) => ctx.notice(me, from.uid, "That does not look like a certificate fingerprint."),
|
||||
Err(CertError::NoAccount | CertError::Internal) => ctx.notice(me, from.uid, "Could not add the fingerprint, please try again later."),
|
||||
}
|
||||
}
|
||||
Some("DEL") | Some("REMOVE") => {
|
||||
let (Some(password), Some(fp)) = (args.get(2), args.get(3)) else {
|
||||
ctx.notice(me, from.uid, "Syntax: CERT DEL <password> <fingerprint>");
|
||||
return;
|
||||
};
|
||||
let Some(account) = auth(db, password) else {
|
||||
ctx.notice(me, from.uid, "Invalid password.");
|
||||
return;
|
||||
};
|
||||
match db.certfp_del(&account, fp) {
|
||||
Ok(true) => ctx.notice(me, from.uid, format!("Removed fingerprint \x02{fp}\x02.")),
|
||||
Ok(false) => ctx.notice(me, from.uid, "No such fingerprint is registered to your account."),
|
||||
Err(_) => ctx.notice(me, from.uid, "Could not remove the fingerprint, please try again later."),
|
||||
}
|
||||
}
|
||||
_ => ctx.notice(me, from.uid, "Syntax: CERT ADD|DEL|LIST <password> [fingerprint]"),
|
||||
}
|
||||
}
|
||||
}
|
||||
316
modules/protocol/inspircd.rs
Normal file
316
modules/protocol/inspircd.rs
Normal file
|
|
@ -0,0 +1,316 @@
|
|||
// InspIRCd spanning-tree link protocol. Handshake + UID + PING mirror the
|
||||
// sequence in Network-Links (protocols/inspircd.py); mode/burst details get
|
||||
// firmed up against a live insp4 uplink.
|
||||
use super::{NetAction, NetEvent, Protocol};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
pub struct InspIrcd {
|
||||
sid: String,
|
||||
name: String,
|
||||
password: String,
|
||||
protocol: u32,
|
||||
ts: u64,
|
||||
}
|
||||
|
||||
impl InspIrcd {
|
||||
pub fn new(name: String, sid: String, password: String, protocol: u32, ts: u64) -> Self {
|
||||
Self { sid, name, password, protocol, ts }
|
||||
}
|
||||
|
||||
fn from_us(&self, cmd: String) -> String {
|
||||
format!(":{} {}", self.sid, cmd)
|
||||
}
|
||||
}
|
||||
|
||||
impl Protocol for InspIrcd {
|
||||
fn handshake(&mut self) -> Vec<String> {
|
||||
vec![
|
||||
format!("CAPAB START {}", self.protocol),
|
||||
format!("CAPAB CAPABILITIES :PROTOCOL={}", self.protocol),
|
||||
"CAPAB END".to_string(),
|
||||
format!("SERVER {} {} {} :{}", self.name, self.password, self.sid, "Federated Services"),
|
||||
]
|
||||
}
|
||||
|
||||
fn parse(&mut self, line: &str) -> Vec<NetEvent> {
|
||||
// Strip an optional IRCv3 message-tag prefix (@k=v;… ) — insp tags PRIVMSGs
|
||||
// with time/msgid, and it sits before the :source.
|
||||
let line = match line.strip_prefix('@') {
|
||||
Some(rest) => rest.splitn(2, ' ').nth(1).unwrap_or(""),
|
||||
None => line,
|
||||
};
|
||||
let (source, rest) = match line.strip_prefix(':') {
|
||||
Some(s) => {
|
||||
let mut it = s.splitn(2, ' ');
|
||||
(Some(it.next().unwrap_or("").to_string()), it.next().unwrap_or(""))
|
||||
}
|
||||
None => (None, line),
|
||||
};
|
||||
let mut tokens = rest.split(' ');
|
||||
let cmd = match tokens.next() {
|
||||
Some(c) => c,
|
||||
None => return vec![],
|
||||
};
|
||||
match cmd.to_ascii_uppercase().as_str() {
|
||||
"SERVER" => vec![NetEvent::Registered],
|
||||
"ENDBURST" => vec![NetEvent::EndBurst],
|
||||
"PING" => {
|
||||
let token = tokens
|
||||
.next()
|
||||
.unwrap_or("")
|
||||
.trim_start_matches(':')
|
||||
.to_string();
|
||||
vec![NetEvent::Ping { token, from: source }]
|
||||
}
|
||||
"PRIVMSG" => {
|
||||
let to = tokens.next().unwrap_or("").to_string();
|
||||
vec![NetEvent::Privmsg {
|
||||
from: source.unwrap_or_default(),
|
||||
to,
|
||||
text: trailing(rest),
|
||||
}]
|
||||
}
|
||||
// UID <uuid> <nickts> <nick> … — track who's online so services can
|
||||
// resolve a sender's current nick.
|
||||
"UID" => {
|
||||
let a: Vec<&str> = tokens.collect();
|
||||
match (a.first(), a.get(2)) {
|
||||
(Some(uid), Some(nick)) => {
|
||||
vec![NetEvent::UserConnect { uid: uid.to_string(), nick: nick.to_string() }]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
// :<uid> NICK <newnick> <newts> — keep the sender's current nick
|
||||
// fresh, so nick-based commands (IDENTIFY/REGISTER) act on who they
|
||||
// are now, not their nick at burst time (e.g. after a guest rename).
|
||||
"NICK" => match (source, tokens.next()) {
|
||||
(Some(uid), Some(nick)) if !nick.is_empty() => {
|
||||
vec![NetEvent::NickChange { uid, nick: nick.to_string() }]
|
||||
}
|
||||
_ => vec![],
|
||||
},
|
||||
// FJOIN <chan> <ts> <modes> [params] :<members> — channel create/burst.
|
||||
// Each member is "<prefixes>,<uid>"; surface a Join for each.
|
||||
"FJOIN" => {
|
||||
let chan = tokens.next().unwrap_or("").to_string();
|
||||
if chan.is_empty() {
|
||||
vec![]
|
||||
} else {
|
||||
let mut out = vec![NetEvent::ChannelCreate { channel: chan.clone() }];
|
||||
// Members are "<prefixes>,<uid>[:<membid>]"; take the uid.
|
||||
for m in trailing(rest).split_whitespace() {
|
||||
if let Some((_, member)) = m.split_once(',') {
|
||||
let uid = member.split(':').next().unwrap_or("");
|
||||
if !uid.is_empty() {
|
||||
out.push(NetEvent::Join { uid: uid.to_string(), channel: chan.clone() });
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
// :<uid> IJOIN <chan> — a single user joining an existing channel.
|
||||
"IJOIN" => match (source.as_deref(), tokens.next()) {
|
||||
(Some(uid), Some(chan)) if chan.starts_with('#') => {
|
||||
vec![NetEvent::Join { uid: uid.to_string(), channel: chan.to_string() }]
|
||||
}
|
||||
_ => vec![],
|
||||
},
|
||||
// :<src> FMODE <chan> <ts> <modes> [params] — a channel mode change.
|
||||
// Skip changes we made ourselves so enforcement can't loop.
|
||||
"FMODE" => {
|
||||
let a: Vec<&str> = tokens.collect();
|
||||
match (source.as_deref(), a.first(), a.get(2)) {
|
||||
// Our own uids (server SID + pseudoclients) share our SID prefix.
|
||||
(Some(src), Some(chan), Some(modes)) if !src.starts_with(self.sid.as_str()) && chan.starts_with('#') => {
|
||||
vec![NetEvent::ChannelModeChange { channel: chan.to_string(), modes: modes.to_string() }]
|
||||
}
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
"QUIT" => vec![NetEvent::Quit { uid: source.unwrap_or_default() }],
|
||||
// account-registration relay from an ircd:
|
||||
// ACCTREGISTER <reqid> <origin> <kind> <account> <p2> :<p3>
|
||||
"ACCTREGISTER" => {
|
||||
let a: Vec<&str> = tokens.by_ref().take(5).collect();
|
||||
if a.len() == 5 {
|
||||
vec![NetEvent::AccountRequest {
|
||||
reqid: a[0].to_string(),
|
||||
origin: a[1].to_string(),
|
||||
kind: a[2].to_string(),
|
||||
account: a[3].to_string(),
|
||||
p2: a[4].to_string(),
|
||||
p3: trailing(rest),
|
||||
}]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
// ENCAP <target> <subcmd> … — we only care about relayed SASL:
|
||||
// ENCAP <target> SASL <client> <agent> <mode> [data…]
|
||||
"ENCAP" => {
|
||||
let _target = tokens.next();
|
||||
match tokens.next().map(|s| s.to_ascii_uppercase()).as_deref() {
|
||||
Some("SASL") => {
|
||||
let p: Vec<&str> = tokens.collect();
|
||||
if p.len() >= 3 {
|
||||
vec![NetEvent::Sasl {
|
||||
client: p[0].to_string(),
|
||||
agent: p[1].to_string(),
|
||||
mode: p[2].to_string(),
|
||||
data: p[3..].iter().map(|s| s.to_string()).collect(),
|
||||
}]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
_ => vec![NetEvent::Unknown { line: line.to_string() }],
|
||||
}
|
||||
}
|
||||
_ => vec![NetEvent::Unknown { line: line.to_string() }],
|
||||
}
|
||||
}
|
||||
|
||||
fn serialize(&mut self, action: &NetAction) -> Vec<String> {
|
||||
match action {
|
||||
NetAction::Burst => vec![self.from_us(format!("BURST {}", self.ts))],
|
||||
NetAction::EndBurst => vec![self.from_us("ENDBURST".to_string())],
|
||||
NetAction::Pong { token, from } => {
|
||||
let dest = from.clone().unwrap_or_else(|| self.sid.clone());
|
||||
vec![self.from_us(format!("PONG {} {}", dest, token))]
|
||||
}
|
||||
// insp4 UID: uuid nickts nick realhost disphost realuser dispuser ip signonts +modes :gecos
|
||||
// (both a real AND a displayed user field — see m_spanningtree/uid.cpp Builder).
|
||||
NetAction::IntroduceUser { uid, nick, ident, host, gecos } => vec![self.from_us(format!(
|
||||
"UID {uid} {ts} {nick} {host} {host} {ident} {ident} 0.0.0.0 {ts} +i :{gecos}",
|
||||
uid = uid, ts = self.ts, nick = nick, host = host, ident = ident, gecos = gecos
|
||||
))],
|
||||
NetAction::Privmsg { from, to, text } => {
|
||||
vec![format!(":{} PRIVMSG {} :{}", from, to, text)]
|
||||
}
|
||||
NetAction::Notice { from, to, text } => {
|
||||
vec![format!(":{} NOTICE {} :{}", from, to, text)]
|
||||
}
|
||||
// ACCTREGRESULT <reqid> <kind> <account> <status> <code> :<message>
|
||||
NetAction::AccountResponse { reqid, kind, account, status, code, message } => {
|
||||
vec![self.from_us(format!(
|
||||
"ACCTREGRESULT {} {} {} {} {} :{}",
|
||||
reqid, kind, account, status, code, message
|
||||
))]
|
||||
}
|
||||
// ENCAP * SASL <agent> <client> <mode> [data…]
|
||||
NetAction::Sasl { agent, client, mode, data } => {
|
||||
let mut line = format!("ENCAP * SASL {} {} {}", agent, client, mode);
|
||||
for d in data {
|
||||
line.push(' ');
|
||||
line.push_str(d);
|
||||
}
|
||||
vec![self.from_us(line)]
|
||||
}
|
||||
// METADATA <target> <key> :<value> — "*" is server-global metadata.
|
||||
NetAction::Metadata { target, key, value } => {
|
||||
vec![self.from_us(format!("METADATA {} {} :{}", target, key, value))]
|
||||
}
|
||||
// SVSNICK <uid> <newnick> <nickts> — the new nick takes the current
|
||||
// time as its TS so it wins any collision resolution.
|
||||
NetAction::ForceNick { uid, nick } => {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(self.ts);
|
||||
vec![self.from_us(format!("SVSNICK {} {} {}", uid, nick, now))]
|
||||
}
|
||||
// FMODE <chan> <ts> <modes>. The ircd drops an FMODE whose TS is newer
|
||||
// than the channel's, so we send TS 1 to guarantee it applies. Sourced
|
||||
// from the given pseudoclient (e.g. ChanServ) so users see who set it,
|
||||
// or from the services server when `from` is empty.
|
||||
NetAction::ChannelMode { from, channel, modes } => {
|
||||
let cmd = format!("FMODE {} 1 {}", channel, modes);
|
||||
if from.is_empty() {
|
||||
vec![self.from_us(cmd)]
|
||||
} else {
|
||||
vec![format!(":{} {}", from, cmd)]
|
||||
}
|
||||
}
|
||||
NetAction::Raw(s) => vec![s.clone()],
|
||||
// Internal: the link layer handles this before serialization.
|
||||
NetAction::DeferRegister { .. } => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn sid(&self) -> &str {
|
||||
&self.sid
|
||||
}
|
||||
}
|
||||
|
||||
// The IRC "trailing" argument: everything after the first " :", else the last word.
|
||||
fn trailing(rest: &str) -> String {
|
||||
match rest.find(" :") {
|
||||
Some(i) => rest[i + 2..].to_string(),
|
||||
None => rest.rsplit(' ').next().unwrap_or("").to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn proto() -> InspIrcd {
|
||||
InspIrcd::new("services.test".into(), "42S".into(), "pw".into(), 1206, 1)
|
||||
}
|
||||
|
||||
// A remote nick change must surface as a NickChange for the source uid, or
|
||||
// nick-based commands act on a stale nick.
|
||||
#[test]
|
||||
fn parses_nick_change() {
|
||||
let ev = proto().parse(":0IRAAAAAB NICK newnick 1783833000");
|
||||
assert!(
|
||||
matches!(ev.as_slice(), [NetEvent::NickChange { uid, nick }] if uid == "0IRAAAAAB" && nick == "newnick"),
|
||||
"{ev:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// A UID burst introduces the user under their current nick.
|
||||
#[test]
|
||||
fn parses_uid_burst() {
|
||||
let ev = proto().parse(":0IR UID 0IRAAAAAB 1783833000 alice host host user user 0.0.0.0 1783833000 +i :real");
|
||||
assert!(
|
||||
matches!(ev.as_slice(), [NetEvent::UserConnect { uid, nick }] if uid == "0IRAAAAAB" && nick == "alice"),
|
||||
"{ev:?}"
|
||||
);
|
||||
}
|
||||
|
||||
// FJOIN (channel create/burst) surfaces as ChannelCreate for the channel, and
|
||||
// the member's uid is taken without its :membid suffix.
|
||||
#[test]
|
||||
fn parses_fjoin_as_channel_create() {
|
||||
let ev = proto().parse(":0IR FJOIN #chan 1783845132 +tn :o,0IRAAAAAB:0");
|
||||
assert!(matches!(ev.first(), Some(NetEvent::ChannelCreate { channel }) if channel == "#chan"), "{ev:?}");
|
||||
assert!(ev.iter().any(|e| matches!(e, NetEvent::Join { uid, .. } if uid == "0IRAAAAAB")), "{ev:?}");
|
||||
}
|
||||
|
||||
// A peer FMODE surfaces as a mode change; our own (sid 42S) is filtered out.
|
||||
#[test]
|
||||
fn parses_fmode_and_filters_own() {
|
||||
let ev = proto().parse(":0IRAAAAAB FMODE #chan 1783845132 +m");
|
||||
assert!(
|
||||
matches!(ev.as_slice(), [NetEvent::ChannelModeChange { channel, modes }] if channel == "#chan" && modes == "+m"),
|
||||
"{ev:?}"
|
||||
);
|
||||
let ev = proto().parse(":42S FMODE #chan 1783845132 -m");
|
||||
assert!(!ev.iter().any(|e| matches!(e, NetEvent::ChannelModeChange { .. })), "own change filtered: {ev:?}");
|
||||
}
|
||||
|
||||
// FJOIN members and IJOIN both surface as Join events.
|
||||
#[test]
|
||||
fn parses_joins() {
|
||||
let ev = proto().parse(":0IR FJOIN #chan 1783845132 +nt :o,0IRAAAAAB ,0IRAAAAAC");
|
||||
assert!(matches!(ev.first(), Some(NetEvent::ChannelCreate { channel }) if channel == "#chan"));
|
||||
let joins: Vec<&str> = ev.iter().filter_map(|e| match e {
|
||||
NetEvent::Join { uid, .. } => Some(uid.as_str()),
|
||||
_ => None,
|
||||
}).collect();
|
||||
assert_eq!(joins, ["0IRAAAAAB", "0IRAAAAAC"]);
|
||||
|
||||
let ev = proto().parse(":0IRAAAAAD IJOIN #chan");
|
||||
assert!(matches!(ev.as_slice(), [NetEvent::Join { uid, channel }] if uid == "0IRAAAAAD" && channel == "#chan"), "{ev:?}");
|
||||
}
|
||||
}
|
||||
78
modules/protocol/mod.rs
Normal file
78
modules/protocol/mod.rs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// Protocol abstraction. The engine only ever sees NetEvent / NetAction; raw
|
||||
// server-to-server lines live entirely behind a Protocol impl. Adding another
|
||||
// ircd later means one new module, engine untouched.
|
||||
pub mod inspircd;
|
||||
|
||||
// Normalized inbound facts, translated from the uplink's raw lines.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NetEvent {
|
||||
Registered,
|
||||
EndBurst,
|
||||
Ping { token: String, from: Option<String> },
|
||||
Privmsg { from: String, to: String, text: String },
|
||||
UserConnect { uid: String, nick: String },
|
||||
NickChange { uid: String, nick: String },
|
||||
// A channel was created or bursted (InspIRCd FJOIN). Subsequent single joins
|
||||
// arrive as IJOIN and are not surfaced.
|
||||
ChannelCreate { channel: String },
|
||||
// A user joined a channel (an FJOIN member or an IJOIN), for auto-op.
|
||||
Join { uid: String, channel: String },
|
||||
// A channel's modes changed (FMODE), for enforcing mode locks. Our own
|
||||
// changes are filtered out by the protocol layer.
|
||||
ChannelModeChange { channel: String, modes: String },
|
||||
Quit { uid: String },
|
||||
// An ircd relaying an IRCv3 account-registration request to us as the authority.
|
||||
AccountRequest { reqid: String, origin: String, kind: String, account: String, p2: String, p3: String },
|
||||
// An ircd relaying a SASL exchange step to us (the SASL agent). mode = H/S/C/D.
|
||||
Sasl { client: String, agent: String, mode: String, data: Vec<String> },
|
||||
Unknown { line: String },
|
||||
}
|
||||
|
||||
// Normalized outbound intents the engine wants performed on the network.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NetAction {
|
||||
Burst,
|
||||
EndBurst,
|
||||
Pong { token: String, from: Option<String> },
|
||||
IntroduceUser { uid: String, nick: String, ident: String, host: String, gecos: String },
|
||||
Privmsg { from: String, to: String, text: String },
|
||||
Notice { from: String, to: String, text: String },
|
||||
AccountResponse { reqid: String, kind: String, account: String, status: String, code: String, message: String },
|
||||
// A SASL exchange step back to the ircd, sourced from our SASL agent. mode = C/D.
|
||||
Sasl { agent: String, client: String, mode: String, data: Vec<String> },
|
||||
// Publish network state to the uplink: target "*" is server-global (e.g. the
|
||||
// advertised SASL mechanism list), otherwise a user uid (e.g. their account).
|
||||
Metadata { target: String, key: String, value: String },
|
||||
// Force a user's nick (SVSNICK), e.g. renaming to a guest nick on logout.
|
||||
// The protocol stamps the new nick's timestamp.
|
||||
ForceNick { uid: String, nick: String },
|
||||
// Set channel modes from services, e.g. +r on a registered channel. `from` is
|
||||
// the pseudoclient uid to source it from (empty = the services server). The
|
||||
// protocol stamps a timestamp the ircd will accept.
|
||||
ChannelMode { from: String, channel: String, modes: String },
|
||||
Raw(String),
|
||||
// Internal only, never serialized to the wire: a registration whose password
|
||||
// still needs its (expensive) key derivation. The link layer runs the
|
||||
// derivation off-thread, then calls Engine::complete_register.
|
||||
DeferRegister { account: String, password: String, email: Option<String>, reply: RegReply },
|
||||
}
|
||||
|
||||
// How to answer a registration once its credentials have been derived.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum RegReply {
|
||||
// IRCv3 account-registration relay: answer the requesting ircd.
|
||||
Relay { reqid: String, kind: String },
|
||||
// NickServ REGISTER: NOTICE the requesting user, logging them in on success.
|
||||
NickServ { agent: String, uid: String, nick: String },
|
||||
}
|
||||
|
||||
pub trait Protocol: Send {
|
||||
/// Lines to send immediately on connect (auth / capability negotiation).
|
||||
fn handshake(&mut self) -> Vec<String>;
|
||||
/// One raw inbound line -> zero or more normalized events.
|
||||
fn parse(&mut self, line: &str) -> Vec<NetEvent>;
|
||||
/// One normalized action -> the raw line(s) that realise it.
|
||||
fn serialize(&mut self, action: &NetAction) -> Vec<String>;
|
||||
/// Our own server id, used as the source prefix for server-sourced lines.
|
||||
fn sid(&self) -> &str;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue