forked from lavina/lavina
Compare commits
2 Commits
fa880af66c
...
7cb541f02e
Author | SHA1 | Date |
---|---|---|
Nikita Vilunov | 7cb541f02e | |
Nikita Vilunov | bafcd97632 |
|
@ -1270,9 +1270,11 @@ dependencies = [
|
||||||
"nonempty",
|
"nonempty",
|
||||||
"prometheus",
|
"prometheus",
|
||||||
"proto-irc",
|
"proto-irc",
|
||||||
|
"sasl",
|
||||||
"serde",
|
"serde",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"tracing-subscriber",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|
|
@ -11,7 +11,10 @@ serde.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
prometheus.workspace = true
|
prometheus.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
|
|
||||||
nonempty.workspace = true
|
nonempty.workspace = true
|
||||||
proto-irc = { path = "../proto-irc" }
|
|
||||||
bitflags = "2.4.1"
|
bitflags = "2.4.1"
|
||||||
|
proto-irc = { path = "../proto-irc" }
|
||||||
|
sasl = { path = "../sasl" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
use bitflags::bitflags;
|
use bitflags::bitflags;
|
||||||
|
|
||||||
bitflags! {
|
bitflags! {
|
||||||
|
#[derive(Debug)]
|
||||||
pub struct Capabilities: u32 {
|
pub struct Capabilities: u32 {
|
||||||
const None = 0;
|
const None = 0;
|
||||||
const Sasl = 1 << 0;
|
const Sasl = 1 << 0;
|
||||||
|
|
|
@ -2,13 +2,10 @@ use std::collections::HashMap;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use cap::Capabilities;
|
|
||||||
use futures_util::future::join_all;
|
use futures_util::future::join_all;
|
||||||
use nonempty::nonempty;
|
use nonempty::nonempty;
|
||||||
use nonempty::NonEmpty;
|
use nonempty::NonEmpty;
|
||||||
use prometheus::{IntCounter, IntGauge, Registry as MetricsRegistry};
|
use prometheus::{IntCounter, IntGauge, Registry as MetricsRegistry};
|
||||||
use proto_irc::client::CapabilitySubcommand;
|
|
||||||
use proto_irc::server::CapSubBody;
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tokio::io::AsyncReadExt;
|
use tokio::io::AsyncReadExt;
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
|
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
|
||||||
|
@ -21,13 +18,18 @@ use lavina_core::prelude::*;
|
||||||
use lavina_core::repo::Storage;
|
use lavina_core::repo::Storage;
|
||||||
use lavina_core::room::{RoomId, RoomInfo, RoomRegistry};
|
use lavina_core::room::{RoomId, RoomInfo, RoomRegistry};
|
||||||
use lavina_core::terminator::Terminator;
|
use lavina_core::terminator::Terminator;
|
||||||
|
use proto_irc::client::CapabilitySubcommand;
|
||||||
use proto_irc::client::{client_message, ClientMessage};
|
use proto_irc::client::{client_message, ClientMessage};
|
||||||
|
use proto_irc::server::CapSubBody;
|
||||||
use proto_irc::server::{AwayStatus, ServerMessage, ServerMessageBody};
|
use proto_irc::server::{AwayStatus, ServerMessage, ServerMessageBody};
|
||||||
use proto_irc::user::PrefixedNick;
|
use proto_irc::user::PrefixedNick;
|
||||||
use proto_irc::{Chan, Recipient};
|
use proto_irc::{Chan, Recipient};
|
||||||
|
use sasl::AuthBody;
|
||||||
|
|
||||||
mod cap;
|
mod cap;
|
||||||
|
|
||||||
|
use crate::cap::Capabilities;
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
pub struct ServerConfig {
|
pub struct ServerConfig {
|
||||||
pub listen_on: SocketAddr,
|
pub listen_on: SocketAddr,
|
||||||
|
@ -68,8 +70,8 @@ async fn handle_socket(
|
||||||
log::debug!("User registered");
|
log::debug!("User registered");
|
||||||
handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user).await?;
|
handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user).await?;
|
||||||
}
|
}
|
||||||
Err(_) => {
|
Err(err) => {
|
||||||
log::debug!("Registration failed");
|
log::debug!("Registration failed: {err}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -83,19 +85,6 @@ async fn handle_registration<'a>(
|
||||||
storage: &mut Storage,
|
storage: &mut Storage,
|
||||||
config: &ServerConfig,
|
config: &ServerConfig,
|
||||||
) -> Result<RegisteredUser> {
|
) -> Result<RegisteredUser> {
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::Notice {
|
|
||||||
first_target: "*".into(),
|
|
||||||
rest_targets: vec![],
|
|
||||||
text: "Welcome to my server!".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
|
|
||||||
let mut buffer = vec![];
|
let mut buffer = vec![];
|
||||||
|
|
||||||
let mut future_nickname: Option<Str> = None;
|
let mut future_nickname: Option<Str> = None;
|
||||||
|
@ -104,6 +93,8 @@ async fn handle_registration<'a>(
|
||||||
let mut cap_negotiation_in_progress = false; // if true, expect `CAP END` to complete registration
|
let mut cap_negotiation_in_progress = false; // if true, expect `CAP END` to complete registration
|
||||||
|
|
||||||
let mut pass: Option<Str> = None;
|
let mut pass: Option<Str> = None;
|
||||||
|
let mut authentication_started = false;
|
||||||
|
let mut validated_user = None;
|
||||||
|
|
||||||
let user = loop {
|
let user = loop {
|
||||||
let res = read_irc_message(reader, &mut buffer).await;
|
let res = read_irc_message(reader, &mut buffer).await;
|
||||||
|
@ -156,28 +147,79 @@ async fn handle_registration<'a>(
|
||||||
CapabilitySubcommand::Req(caps) => {
|
CapabilitySubcommand::Req(caps) => {
|
||||||
cap_negotiation_in_progress = true;
|
cap_negotiation_in_progress = true;
|
||||||
let mut acked = vec![];
|
let mut acked = vec![];
|
||||||
|
let mut naked = vec![];
|
||||||
for cap in caps {
|
for cap in caps {
|
||||||
if &*cap.name == "sasl" {
|
if &*cap.name == "sasl" {
|
||||||
if cap.to_disable {
|
if cap.to_disable {
|
||||||
enabled_capabilities &= !Capabilities::Sasl;
|
enabled_capabilities &= !Capabilities::Sasl;
|
||||||
} else {
|
} else {
|
||||||
enabled_capabilities &= Capabilities::Sasl;
|
enabled_capabilities |= Capabilities::Sasl;
|
||||||
}
|
}
|
||||||
acked.push(cap);
|
acked.push(cap);
|
||||||
|
} else {
|
||||||
|
naked.push(cap);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
let mut ack_body = String::new();
|
||||||
|
for cap in acked {
|
||||||
|
if cap.to_disable {
|
||||||
|
ack_body.push('-');
|
||||||
|
}
|
||||||
|
ack_body += &*cap.name;
|
||||||
|
}
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::Cap {
|
||||||
|
target: future_nickname.clone().unwrap_or_else(|| "*".into()),
|
||||||
|
subcmd: CapSubBody::Ack(ack_body.into()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
}
|
||||||
|
CapabilitySubcommand::End => {
|
||||||
|
let Some((username, realname)) = future_username else {
|
||||||
|
todo!()
|
||||||
|
};
|
||||||
|
let Some(nickname) = future_nickname.clone() else {
|
||||||
|
todo!()
|
||||||
|
};
|
||||||
|
let candidate_user = RegisteredUser {
|
||||||
|
nickname,
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
};
|
||||||
|
dbg!(&enabled_capabilities);
|
||||||
|
dbg!(&validated_user);
|
||||||
|
if enabled_capabilities.contains(Capabilities::Sasl)
|
||||||
|
&& validated_user.as_ref() == Some(&candidate_user.nickname)
|
||||||
|
{
|
||||||
|
break Ok(candidate_user);
|
||||||
|
} else {
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
|
break Ok(candidate_user);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
CapabilitySubcommand::End => {}
|
|
||||||
},
|
},
|
||||||
ClientMessage::Nick { nickname } => {
|
ClientMessage::Nick { nickname } => {
|
||||||
if cap_negotiation_in_progress {
|
if cap_negotiation_in_progress {
|
||||||
future_nickname = Some(nickname);
|
future_nickname = Some(nickname);
|
||||||
} else if let Some((username, realname)) = future_username {
|
} else if let Some((username, realname)) = future_username.clone() {
|
||||||
break Ok(RegisteredUser {
|
let candidate_user = RegisteredUser {
|
||||||
nickname,
|
nickname,
|
||||||
username,
|
username,
|
||||||
realname,
|
realname,
|
||||||
});
|
};
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
|
break Ok(candidate_user);
|
||||||
} else {
|
} else {
|
||||||
future_nickname = Some(nickname);
|
future_nickname = Some(nickname);
|
||||||
}
|
}
|
||||||
|
@ -186,40 +228,96 @@ async fn handle_registration<'a>(
|
||||||
if cap_negotiation_in_progress {
|
if cap_negotiation_in_progress {
|
||||||
future_username = Some((username, realname));
|
future_username = Some((username, realname));
|
||||||
} else if let Some(nickname) = future_nickname.clone() {
|
} else if let Some(nickname) = future_nickname.clone() {
|
||||||
break Ok(RegisteredUser {
|
let candidate_user = RegisteredUser {
|
||||||
nickname,
|
nickname,
|
||||||
username,
|
username,
|
||||||
realname,
|
realname,
|
||||||
});
|
};
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
|
break Ok(candidate_user);
|
||||||
} else {
|
} else {
|
||||||
future_username = Some((username, realname));
|
future_username = Some((username, realname));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ClientMessage::Authenticate(body) => {
|
||||||
|
if !authentication_started {
|
||||||
|
tracing::debug!("Received authentication request");
|
||||||
|
if &*body == "PLAIN" {
|
||||||
|
tracing::debug!("Authentication request with method PLAIN");
|
||||||
|
authentication_started = true;
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::Authenticate("+".into()),
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
} else {
|
||||||
|
// TODO respond with 904
|
||||||
|
todo!();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let body = AuthBody::from_str(body.as_bytes())?;
|
||||||
|
auth_user(storage, &body.login, &body.password).await?;
|
||||||
|
let login: Str = body.login.into();
|
||||||
|
validated_user = Some(login.clone());
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::N900LoggedIn {
|
||||||
|
nick: login.clone(),
|
||||||
|
address: login.clone(),
|
||||||
|
account: login.clone(),
|
||||||
|
message: format!("You are now logged in as {}", login).into(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::N903SaslSuccess {
|
||||||
|
nick: login.clone(),
|
||||||
|
message: "SASL authentication successful".into(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
}
|
||||||
|
// TODO handle abortion of authentication
|
||||||
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
buffer.clear();
|
buffer.clear();
|
||||||
}?;
|
}?;
|
||||||
|
// TODO properly implement session temination
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
let stored_user = storage.retrieve_user_by_name(&*user.nickname).await?;
|
async fn auth_user(storage: &mut Storage, login: &str, plain_password: &str) -> Result<()> {
|
||||||
|
let stored_user = storage.retrieve_user_by_name(login).await?;
|
||||||
|
|
||||||
let stored_user = match stored_user {
|
let stored_user = match stored_user {
|
||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
None => {
|
None => {
|
||||||
log::info!("User '{}' not found", user.nickname);
|
log::info!("User '{}' not found", login);
|
||||||
return Err(anyhow!("no user found"));
|
return Err(anyhow!("no user found"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if stored_user.password.is_none() {
|
let Some(expected_password) = stored_user.password else {
|
||||||
log::info!("Password not defined for user '{}'", user.nickname);
|
log::info!("Password not defined for user '{}'", login);
|
||||||
return Err(anyhow!("password is not defined"));
|
return Err(anyhow!("password is not defined"));
|
||||||
}
|
};
|
||||||
if stored_user.password.as_deref() != pass.as_deref() {
|
if expected_password != plain_password {
|
||||||
log::info!("Incorrect password supplied for user '{}'", user.nickname);
|
log::info!("Incorrect password supplied for user '{}'", login);
|
||||||
return Err(anyhow!("passwords do not match"));
|
return Err(anyhow!("passwords do not match"));
|
||||||
}
|
}
|
||||||
// TODO properly implement session temination
|
Ok(())
|
||||||
|
|
||||||
Ok(user)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_registered_socket<'a>(
|
async fn handle_registered_socket<'a>(
|
||||||
|
@ -236,6 +334,19 @@ async fn handle_registered_socket<'a>(
|
||||||
let player_id = PlayerId::from(user.nickname.clone())?;
|
let player_id = PlayerId::from(user.nickname.clone())?;
|
||||||
let mut connection = players.connect_to_player(player_id.clone()).await;
|
let mut connection = players.connect_to_player(player_id.clone()).await;
|
||||||
|
|
||||||
|
// ServerMessage {
|
||||||
|
// tags: vec![],
|
||||||
|
// sender: Some(config.server_name.clone().into()),
|
||||||
|
// body: ServerMessageBody::Notice {
|
||||||
|
// first_target: "*".into(),
|
||||||
|
// rest_targets: vec![],
|
||||||
|
// text: "Welcome to my server!".into(),
|
||||||
|
// },
|
||||||
|
// }
|
||||||
|
// .write_async(writer)
|
||||||
|
// .await?;
|
||||||
|
// writer.flush().await?;
|
||||||
|
|
||||||
ServerMessage {
|
ServerMessage {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
sender: Some(config.server_name.clone()),
|
sender: Some(config.server_name.clone()),
|
||||||
|
|
|
@ -39,6 +39,7 @@ impl<'a> TestScope<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn expect(&mut self, str: &str) -> Result<()> {
|
async fn expect(&mut self, str: &str) -> Result<()> {
|
||||||
|
tracing::debug!("Expecting {}", str);
|
||||||
let len = tokio::time::timeout(self.timeout, read_irc_message(&mut self.reader, &mut self.buffer)).await??;
|
let len = tokio::time::timeout(self.timeout, read_irc_message(&mut self.reader, &mut self.buffer)).await??;
|
||||||
assert_eq!(std::str::from_utf8(&self.buffer[..len - 2])?, str);
|
assert_eq!(std::str::from_utf8(&self.buffer[..len - 2])?, str);
|
||||||
self.buffer.clear();
|
self.buffer.clear();
|
||||||
|
@ -72,6 +73,7 @@ struct TestServer {
|
||||||
}
|
}
|
||||||
impl TestServer {
|
impl TestServer {
|
||||||
async fn start() -> Result<TestServer> {
|
async fn start() -> Result<TestServer> {
|
||||||
|
let _ = tracing_subscriber::fmt::try_init();
|
||||||
let config = ServerConfig {
|
let config = ServerConfig {
|
||||||
listen_on: "127.0.0.1:0".parse().unwrap(),
|
listen_on: "127.0.0.1:0".parse().unwrap(),
|
||||||
server_name: "testserver".into(),
|
server_name: "testserver".into(),
|
||||||
|
@ -109,7 +111,6 @@ async fn scenario_basic() -> Result<()> {
|
||||||
s.send("PASS password").await?;
|
s.send("PASS password").await?;
|
||||||
s.send("NICK tester").await?;
|
s.send("NICK tester").await?;
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
s.send("USER UserName 0 * :Real Name").await?;
|
||||||
s.expect(":testserver NOTICE * :Welcome to my server!").await?;
|
|
||||||
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
|
@ -149,16 +150,15 @@ async fn scenario_cap_full_negotiation() -> Result<()> {
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
s.send("USER UserName 0 * :Real Name").await?;
|
||||||
s.expect(":testserver CAP * LS :sasl=PLAIN").await?;
|
s.expect(":testserver CAP * LS :sasl=PLAIN").await?;
|
||||||
s.send("CAP REQ :sasl").await?;
|
s.send("CAP REQ :sasl").await?;
|
||||||
s.expect(":testserver CAP tester ACK :sasl=PLAIN").await?;
|
s.expect(":testserver CAP tester ACK :sasl").await?;
|
||||||
s.send("AUTHENTICATE PLAIN").await?;
|
s.send("AUTHENTICATE PLAIN").await?;
|
||||||
s.expect("AUTHENTICATE +").await?;
|
s.expect(":testserver AUTHENTICATE +").await?;
|
||||||
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
||||||
s.expect(":testserver 900 tester ??? ??? :You are now logged in as tester").await?;
|
s.expect(":testserver 900 tester tester tester :You are now logged in as tester").await?;
|
||||||
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
s.send("CAP END").await?;
|
||||||
|
|
||||||
s.expect(":testserver NOTICE * :Welcome to my server!").await?;
|
|
||||||
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
|
@ -189,19 +189,18 @@ async fn scenario_cap_short_negotiation() -> Result<()> {
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
let mut stream = TcpStream::connect(server.server.addr).await?;
|
||||||
let mut s = TestScope::new(&mut stream);
|
let mut s = TestScope::new(&mut stream);
|
||||||
|
|
||||||
s.send("CAP REQ :sasl").await?;
|
|
||||||
s.send("NICK tester").await?;
|
s.send("NICK tester").await?;
|
||||||
|
s.send("CAP REQ :sasl").await?;
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
s.send("USER UserName 0 * :Real Name").await?;
|
||||||
s.expect(":testserver CAP tester ACK :sasl=PLAIN").await?;
|
s.expect(":testserver CAP tester ACK :sasl").await?;
|
||||||
s.send("AUTHENTICATE PLAIN").await?;
|
s.send("AUTHENTICATE PLAIN").await?;
|
||||||
s.expect("AUTHENTICATE +").await?;
|
s.expect(":testserver AUTHENTICATE +").await?;
|
||||||
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
||||||
s.expect(":testserver 900 tester ??? ??? :You are now logged in as tester").await?;
|
s.expect(":testserver 900 tester tester tester :You are now logged in as tester").await?;
|
||||||
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
s.send("CAP END").await?;
|
||||||
|
|
||||||
s.expect(":testserver NOTICE * :Welcome to my server!").await?;
|
|
||||||
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
|
|
|
@ -60,6 +60,7 @@ pub enum ClientMessage {
|
||||||
Quit {
|
Quit {
|
||||||
reason: Str,
|
reason: Str,
|
||||||
},
|
},
|
||||||
|
Authenticate(Str),
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn client_message(input: &str) -> Result<ClientMessage> {
|
pub fn client_message(input: &str) -> Result<ClientMessage> {
|
||||||
|
@ -77,6 +78,7 @@ pub fn client_message(input: &str) -> Result<ClientMessage> {
|
||||||
client_message_part,
|
client_message_part,
|
||||||
client_message_privmsg,
|
client_message_privmsg,
|
||||||
client_message_quit,
|
client_message_quit,
|
||||||
|
client_message_authenticate,
|
||||||
)))(input);
|
)))(input);
|
||||||
match res {
|
match res {
|
||||||
Ok((_, e)) => Ok(e),
|
Ok((_, e)) => Ok(e),
|
||||||
|
@ -224,6 +226,13 @@ fn client_message_quit(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
Ok((input, ClientMessage::Quit { reason: reason.into() }))
|
Ok((input, ClientMessage::Quit { reason: reason.into() }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn client_message_authenticate(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
|
let (input, _) = tag("AUTHENTICATE ")(input)?;
|
||||||
|
let (input, body) = token(input)?;
|
||||||
|
|
||||||
|
Ok((input, ClientMessage::Authenticate(body.into())))
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum CapabilitySubcommand {
|
pub enum CapabilitySubcommand {
|
||||||
/// CAP LS {code}
|
/// CAP LS {code}
|
||||||
|
@ -235,7 +244,11 @@ pub enum CapabilitySubcommand {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn capability_subcommand(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
fn capability_subcommand(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
alt((capability_subcommand_ls, capability_subcommand_end))(input)
|
alt((
|
||||||
|
capability_subcommand_ls,
|
||||||
|
capability_subcommand_end,
|
||||||
|
capability_subcommand_req,
|
||||||
|
))(input)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn capability_subcommand_ls(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
fn capability_subcommand_ls(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
|
@ -250,6 +263,31 @@ fn capability_subcommand_ls(input: &str) -> IResult<&str, CapabilitySubcommand>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn capability_subcommand_req(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
|
let (input, _) = tag("REQ ")(input)?;
|
||||||
|
let (input, r) = opt(tag(":"))(input)?;
|
||||||
|
let (input, body) = match r {
|
||||||
|
Some(_) => token(input)?,
|
||||||
|
None => receiver(input)?,
|
||||||
|
};
|
||||||
|
|
||||||
|
let caps = body
|
||||||
|
.split(' ')
|
||||||
|
.map(|cap| {
|
||||||
|
let to_disable = cap.starts_with('-');
|
||||||
|
let name = if to_disable { &cap[1..] } else { &cap[..] };
|
||||||
|
CapReq {
|
||||||
|
to_disable,
|
||||||
|
name: name.into(),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let caps = NonEmpty::from_vec(caps).ok_or_else(|| todo!())?;
|
||||||
|
|
||||||
|
Ok((input, CapabilitySubcommand::Req(caps)))
|
||||||
|
}
|
||||||
|
|
||||||
fn capability_subcommand_end(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
fn capability_subcommand_end(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
let (input, _) = tag("END")(input)?;
|
let (input, _) = tag("END")(input)?;
|
||||||
Ok((input, CapabilitySubcommand::End))
|
Ok((input, CapabilitySubcommand::End))
|
||||||
|
@ -264,6 +302,7 @@ pub struct CapReq {
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use assert_matches::*;
|
use assert_matches::*;
|
||||||
|
use nonempty::nonempty;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -333,6 +372,25 @@ mod test {
|
||||||
message: "Pokasiki !!!".into(),
|
message: "Pokasiki !!!".into(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let result = client_message(input);
|
||||||
|
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn test_client_cap_req() {
|
||||||
|
let input = "CAP REQ :multi-prefix -sasl";
|
||||||
|
let expected = ClientMessage::Capability {
|
||||||
|
subcommand: CapabilitySubcommand::Req(nonempty![
|
||||||
|
CapReq {
|
||||||
|
to_disable: false,
|
||||||
|
name: "multi-prefix".into()
|
||||||
|
},
|
||||||
|
CapReq {
|
||||||
|
to_disable: true,
|
||||||
|
name: "sasl".into()
|
||||||
|
}
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
|
|
|
@ -70,6 +70,7 @@ pub enum ServerMessageBody {
|
||||||
target: Str,
|
target: Str,
|
||||||
subcmd: CapSubBody,
|
subcmd: CapSubBody,
|
||||||
},
|
},
|
||||||
|
Authenticate(Str),
|
||||||
N001Welcome {
|
N001Welcome {
|
||||||
client: Str,
|
client: Str,
|
||||||
text: Str,
|
text: Str,
|
||||||
|
@ -142,6 +143,16 @@ pub enum ServerMessageBody {
|
||||||
client: Str,
|
client: Str,
|
||||||
message: Str,
|
message: Str,
|
||||||
},
|
},
|
||||||
|
N900LoggedIn {
|
||||||
|
nick: Str,
|
||||||
|
address: Str,
|
||||||
|
account: Str,
|
||||||
|
message: Str,
|
||||||
|
},
|
||||||
|
N903SaslSuccess {
|
||||||
|
nick: Str,
|
||||||
|
message: Str,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ServerMessageBody {
|
impl ServerMessageBody {
|
||||||
|
@ -193,8 +204,16 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b" LS :").await?;
|
writer.write_all(b" LS :").await?;
|
||||||
writer.write_all(caps.as_bytes()).await?;
|
writer.write_all(caps.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
|
CapSubBody::Ack(caps) => {
|
||||||
|
writer.write_all(b" ACK :").await?;
|
||||||
|
writer.write_all(caps.as_bytes()).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
ServerMessageBody::Authenticate(body) => {
|
||||||
|
writer.write_all(b"AUTHENTICATE ").await?;
|
||||||
|
writer.write_all(body.as_bytes()).await?;
|
||||||
|
}
|
||||||
ServerMessageBody::N001Welcome { client, text } => {
|
ServerMessageBody::N001Welcome { client, text } => {
|
||||||
writer.write_all(b"001 ").await?;
|
writer.write_all(b"001 ").await?;
|
||||||
writer.write_all(client.as_bytes()).await?;
|
writer.write_all(client.as_bytes()).await?;
|
||||||
|
@ -334,6 +353,22 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b" :").await?;
|
writer.write_all(b" :").await?;
|
||||||
writer.write_all(message.as_bytes()).await?;
|
writer.write_all(message.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
|
ServerMessageBody::N900LoggedIn { nick, address, account, message } => {
|
||||||
|
writer.write_all(b"900 ").await?;
|
||||||
|
writer.write_all(nick.as_bytes()).await?;
|
||||||
|
writer.write_all(b" ").await?;
|
||||||
|
writer.write_all(address.as_bytes()).await?;
|
||||||
|
writer.write_all(b" ").await?;
|
||||||
|
writer.write_all(account.as_bytes()).await?;
|
||||||
|
writer.write_all(b" :").await?;
|
||||||
|
writer.write_all(message.as_bytes()).await?;
|
||||||
|
}
|
||||||
|
ServerMessageBody::N903SaslSuccess { nick, message } => {
|
||||||
|
writer.write_all(b"903 ").await?;
|
||||||
|
writer.write_all(nick.as_bytes()).await?;
|
||||||
|
writer.write_all(b" :").await?;
|
||||||
|
writer.write_all(message.as_bytes()).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -342,6 +377,7 @@ impl ServerMessageBody {
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum CapSubBody {
|
pub enum CapSubBody {
|
||||||
Ls(Str),
|
Ls(Str),
|
||||||
|
Ack(Str),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
@ -355,6 +391,7 @@ fn server_message_body(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
server_message_body_notice,
|
server_message_body_notice,
|
||||||
server_message_body_ping,
|
server_message_body_ping,
|
||||||
server_message_body_pong,
|
server_message_body_pong,
|
||||||
|
server_message_body_cap,
|
||||||
))(input)
|
))(input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -380,12 +417,7 @@ fn server_message_body_ping(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
let (input, _) = tag("PING ")(input)?;
|
let (input, _) = tag("PING ")(input)?;
|
||||||
let (input, token) = token(input)?;
|
let (input, token) = token(input)?;
|
||||||
|
|
||||||
Ok((
|
Ok((input, ServerMessageBody::Ping { token: token.into() }))
|
||||||
input,
|
|
||||||
ServerMessageBody::Ping {
|
|
||||||
token: token.into(),
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn server_message_body_pong(input: &str) -> IResult<&str, ServerMessageBody> {
|
fn server_message_body_pong(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
|
@ -403,6 +435,21 @@ fn server_message_body_pong(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn server_message_body_cap(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
|
let (input, _) = tag("CAP ")(input)?;
|
||||||
|
let (input, from) = receiver(input)?;
|
||||||
|
let (input, _) = tag(" LS :")(input)?;
|
||||||
|
let (input, token) = token(input)?;
|
||||||
|
|
||||||
|
Ok((
|
||||||
|
input,
|
||||||
|
ServerMessageBody::Cap {
|
||||||
|
target: from.into(),
|
||||||
|
subcmd: CapSubBody::Ls(token.into()),
|
||||||
|
},
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use assert_matches::*;
|
use assert_matches::*;
|
||||||
|
@ -427,9 +474,7 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes))
|
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
||||||
.unwrap()
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(bytes, input.as_bytes());
|
assert_eq!(bytes, input.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -449,9 +494,27 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes))
|
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
||||||
.unwrap()
|
assert_eq!(bytes, input.as_bytes());
|
||||||
.unwrap();
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_server_message_cap_ls() {
|
||||||
|
let input = "CAP * LS :sasl\r\n";
|
||||||
|
let expected = ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: None,
|
||||||
|
body: ServerMessageBody::Cap {
|
||||||
|
target: "*".into(),
|
||||||
|
subcmd: CapSubBody::Ls("sasl".into()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let result = server_message(input);
|
||||||
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
|
let mut bytes = vec![];
|
||||||
|
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
||||||
assert_eq!(bytes, input.as_bytes());
|
assert_eq!(bytes, input.as_bytes());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue