forked from lavina/lavina
Compare commits
6 Commits
f85c3bb6ce
...
ce682a842f
Author | SHA1 | Date |
---|---|---|
Nikita Vilunov | ce682a842f | |
Nikita Vilunov | b7d695519e | |
Nikita Vilunov | ed83436501 | |
Nikita Vilunov | 550c8b74b2 | |
Nikita Vilunov | 85fa607e16 | |
Nikita Vilunov | 4dbc68adfe |
|
@ -12,7 +12,7 @@ jobs:
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
uses: https://github.com/actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: fmt
|
command: fmt
|
||||||
args: "--check -p mgmt-api -p lavina-core -p projection-irc"
|
args: "--check -p mgmt-api -p lavina-core -p projection-irc -p projection-xmpp -p sasl"
|
||||||
- name: cargo check
|
- name: cargo check
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
uses: https://github.com/actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
|
|
|
@ -1,3 +1,4 @@
|
||||||
/target
|
/target
|
||||||
/db.sqlite
|
/db.sqlite
|
||||||
.idea/
|
.idea/
|
||||||
|
.DS_Store
|
||||||
|
|
|
@ -163,9 +163,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bitflags"
|
name = "bitflags"
|
||||||
version = "2.4.0"
|
version = "2.4.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
|
checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
@ -1264,14 +1264,17 @@ name = "projection-irc"
|
||||||
version = "0.0.2-dev"
|
version = "0.0.2-dev"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"bitflags 2.4.1",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
"lavina-core",
|
"lavina-core",
|
||||||
"nonempty",
|
"nonempty",
|
||||||
"prometheus",
|
"prometheus",
|
||||||
"proto-irc",
|
"proto-irc",
|
||||||
|
"sasl",
|
||||||
"serde",
|
"serde",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
|
"tracing-subscriber",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
@ -1287,6 +1290,7 @@ dependencies = [
|
||||||
"proto-xmpp",
|
"proto-xmpp",
|
||||||
"quick-xml",
|
"quick-xml",
|
||||||
"rustls-pemfile",
|
"rustls-pemfile",
|
||||||
|
"sasl",
|
||||||
"serde",
|
"serde",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
|
@ -1327,7 +1331,6 @@ version = "0.0.2-dev"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"assert_matches",
|
"assert_matches",
|
||||||
"base64",
|
|
||||||
"derive_more",
|
"derive_more",
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
"quick-xml",
|
"quick-xml",
|
||||||
|
@ -1515,7 +1518,7 @@ version = "0.38.17"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f25469e9ae0f3d0047ca8b93fc56843f38e6774f0914a107ff8b41be8be8e0b7"
|
checksum = "f25469e9ae0f3d0047ca8b93fc56843f38e6774f0914a107ff8b41be8be8e0b7"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bitflags 2.4.0",
|
"bitflags 2.4.1",
|
||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys",
|
"linux-raw-sys",
|
||||||
|
@ -1559,6 +1562,14 @@ version = "1.0.15"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
|
checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sasl"
|
||||||
|
version = "0.0.2-dev"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"base64",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "scopeguard"
|
name = "scopeguard"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
|
@ -1850,7 +1861,7 @@ checksum = "864b869fdf56263f4c95c45483191ea0af340f9f3e3e7b4d57a61c7c87a970db"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atoi",
|
"atoi",
|
||||||
"base64",
|
"base64",
|
||||||
"bitflags 2.4.0",
|
"bitflags 2.4.1",
|
||||||
"byteorder",
|
"byteorder",
|
||||||
"bytes",
|
"bytes",
|
||||||
"crc",
|
"crc",
|
||||||
|
@ -1892,7 +1903,7 @@ checksum = "eb7ae0e6a97fb3ba33b23ac2671a5ce6e3cabe003f451abd5a56e7951d975624"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atoi",
|
"atoi",
|
||||||
"base64",
|
"base64",
|
||||||
"bitflags 2.4.0",
|
"bitflags 2.4.1",
|
||||||
"byteorder",
|
"byteorder",
|
||||||
"crc",
|
"crc",
|
||||||
"dotenvy",
|
"dotenvy",
|
||||||
|
|
|
@ -6,6 +6,7 @@ members = [
|
||||||
"crates/projection-irc",
|
"crates/projection-irc",
|
||||||
"crates/proto-xmpp",
|
"crates/proto-xmpp",
|
||||||
"crates/mgmt-api",
|
"crates/mgmt-api",
|
||||||
|
"crates/sasl",
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
|
@ -29,6 +30,7 @@ prometheus = { version = "0.13.3", default-features = false }
|
||||||
base64 = "0.21.3"
|
base64 = "0.21.3"
|
||||||
lavina-core = { path = "crates/lavina-core" }
|
lavina-core = { path = "crates/lavina-core" }
|
||||||
tracing-subscriber = "0.3.16"
|
tracing-subscriber = "0.3.16"
|
||||||
|
sasl = { path = "crates/sasl" }
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "lavina"
|
name = "lavina"
|
||||||
|
|
|
@ -11,6 +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
|
||||||
|
bitflags = "2.4.1"
|
||||||
proto-irc = { path = "../proto-irc" }
|
proto-irc = { path = "../proto-irc" }
|
||||||
|
sasl = { path = "../sasl" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tracing-subscriber.workspace = true
|
||||||
|
|
|
@ -0,0 +1,9 @@
|
||||||
|
use bitflags::bitflags;
|
||||||
|
|
||||||
|
bitflags! {
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Capabilities: u32 {
|
||||||
|
const None = 0;
|
||||||
|
const Sasl = 1 << 0;
|
||||||
|
}
|
||||||
|
}
|
|
@ -18,10 +18,17 @@ 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;
|
||||||
|
|
||||||
|
use crate::cap::Capabilities;
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
pub struct ServerConfig {
|
pub struct ServerConfig {
|
||||||
|
@ -55,28 +62,16 @@ async fn handle_socket(
|
||||||
let mut reader: BufReader<ReadHalf> = BufReader::new(reader);
|
let mut reader: BufReader<ReadHalf> = BufReader::new(reader);
|
||||||
let mut writer = BufWriter::new(writer);
|
let mut writer = BufWriter::new(writer);
|
||||||
|
|
||||||
ServerMessage {
|
let registered_user: Result<RegisteredUser> =
|
||||||
tags: vec![],
|
handle_registration(&mut reader, &mut writer, &mut storage, &config).await;
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::Notice {
|
|
||||||
first_target: "*".into(),
|
|
||||||
rest_targets: vec![],
|
|
||||||
text: "Welcome to my server!".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.write_async(&mut writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
|
|
||||||
let registered_user: Result<RegisteredUser> = handle_registration(&mut reader, &mut writer, &mut storage).await;
|
|
||||||
|
|
||||||
match registered_user {
|
match registered_user {
|
||||||
Ok(user) => {
|
Ok(user) => {
|
||||||
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}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -88,93 +83,239 @@ async fn handle_registration<'a>(
|
||||||
reader: &mut BufReader<ReadHalf<'a>>,
|
reader: &mut BufReader<ReadHalf<'a>>,
|
||||||
writer: &mut BufWriter<WriteHalf<'a>>,
|
writer: &mut BufWriter<WriteHalf<'a>>,
|
||||||
storage: &mut Storage,
|
storage: &mut Storage,
|
||||||
|
config: &ServerConfig,
|
||||||
) -> Result<RegisteredUser> {
|
) -> Result<RegisteredUser> {
|
||||||
let mut buffer = vec![];
|
let mut buffer = vec![];
|
||||||
|
|
||||||
let mut future_nickname: Option<Str> = None;
|
let mut future_nickname: Option<Str> = None;
|
||||||
let mut future_username: Option<(Str, Str)> = None;
|
let mut future_username: Option<(Str, Str)> = None;
|
||||||
|
let mut enabled_capabilities = Capabilities::None;
|
||||||
|
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;
|
||||||
let res = match res {
|
tracing::trace!("Received message: {:?}", res);
|
||||||
Ok(len) => {
|
let len = match res {
|
||||||
if len == 0 {
|
Ok(len) => len,
|
||||||
log::info!("Terminating socket");
|
|
||||||
break Err(anyhow::Error::msg("EOF"));
|
|
||||||
}
|
|
||||||
match std::str::from_utf8(&buffer[..len - 2]) {
|
|
||||||
Ok(res) => res,
|
|
||||||
Err(e) => break Err(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::warn!("Failed to read from socket: {err}");
|
log::warn!("Failed to read from socket: {err}");
|
||||||
break Err(err.into());
|
break Err(err.into());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
log::debug!("Incoming raw IRC message: '{res}'");
|
if len == 0 {
|
||||||
|
log::info!("Terminating socket");
|
||||||
|
break Err(anyhow::Error::msg("EOF"));
|
||||||
|
}
|
||||||
|
let res = match std::str::from_utf8(&buffer[..len - 2]) {
|
||||||
|
Ok(res) => res,
|
||||||
|
Err(e) => break Err(e.into()),
|
||||||
|
};
|
||||||
|
tracing::trace!("Incoming raw IRC message: '{res}'");
|
||||||
let parsed = client_message(res);
|
let parsed = client_message(res);
|
||||||
match parsed {
|
let msg = match parsed {
|
||||||
Ok(msg) => {
|
Ok(msg) => msg,
|
||||||
log::debug!("Incoming IRC message: {msg:?}");
|
Err(err) => {
|
||||||
match msg {
|
tracing::warn!("Failed to parse IRC message: {err}");
|
||||||
ClientMessage::Pass { password } => {
|
buffer.clear();
|
||||||
pass = Some(password);
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
tracing::debug!("Incoming IRC message: {msg:?}");
|
||||||
|
match msg {
|
||||||
|
ClientMessage::Pass { password } => {
|
||||||
|
pass = Some(password);
|
||||||
|
}
|
||||||
|
ClientMessage::Capability { subcommand } => match subcommand {
|
||||||
|
CapabilitySubcommand::List { code: _ } => {
|
||||||
|
cap_negotiation_in_progress = true;
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::Cap {
|
||||||
|
target: future_nickname.clone().unwrap_or_else(|| "*".into()),
|
||||||
|
subcmd: CapSubBody::Ls("sasl=PLAIN".into()),
|
||||||
|
},
|
||||||
}
|
}
|
||||||
ClientMessage::Nick { nickname } => {
|
.write_async(writer)
|
||||||
if let Some((username, realname)) = future_username {
|
.await?;
|
||||||
break Ok(RegisteredUser {
|
writer.flush().await?;
|
||||||
nickname,
|
}
|
||||||
username,
|
CapabilitySubcommand::Req(caps) => {
|
||||||
realname,
|
cap_negotiation_in_progress = true;
|
||||||
});
|
let mut acked = vec![];
|
||||||
|
let mut naked = vec![];
|
||||||
|
for cap in caps {
|
||||||
|
if &*cap.name == "sasl" {
|
||||||
|
if cap.to_disable {
|
||||||
|
enabled_capabilities &= !Capabilities::Sasl;
|
||||||
|
} else {
|
||||||
|
enabled_capabilities |= Capabilities::Sasl;
|
||||||
|
}
|
||||||
|
acked.push(cap);
|
||||||
} else {
|
} else {
|
||||||
future_nickname = Some(nickname);
|
naked.push(cap);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ClientMessage::User { username, realname } => {
|
let mut ack_body = String::new();
|
||||||
if let Some(nickname) = future_nickname {
|
for cap in acked {
|
||||||
break Ok(RegisteredUser {
|
if cap.to_disable {
|
||||||
nickname,
|
ack_body.push('-');
|
||||||
username,
|
|
||||||
realname,
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
future_username = Some((username, realname));
|
|
||||||
}
|
}
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
ClientMessage::Nick { nickname } => {
|
||||||
|
if cap_negotiation_in_progress {
|
||||||
|
future_nickname = Some(nickname);
|
||||||
|
} else if let Some((username, realname)) = future_username.clone() {
|
||||||
|
let candidate_user = RegisteredUser {
|
||||||
|
nickname,
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
};
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
|
break Ok(candidate_user);
|
||||||
|
} else {
|
||||||
|
future_nickname = Some(nickname);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => {
|
ClientMessage::User { username, realname } => {
|
||||||
log::warn!("Failed to parse IRC message: {err}");
|
if cap_negotiation_in_progress {
|
||||||
|
future_username = Some((username, realname));
|
||||||
|
} else if let Some(nickname) = future_nickname.clone() {
|
||||||
|
let candidate_user = RegisteredUser {
|
||||||
|
nickname,
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
};
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
|
break Ok(candidate_user);
|
||||||
|
} else {
|
||||||
|
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>(
|
||||||
|
|
|
@ -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,96 @@ 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 002 tester :Welcome to Kek Server").await?;
|
||||||
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
|
s.expect(":testserver 004 tester testserver kek-0.1.alpha.3 r CFILPQbcefgijklmnopqrstvz").await?;
|
||||||
|
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
||||||
|
s.expect_nothing().await?;
|
||||||
|
s.send("QUIT :Leaving").await?;
|
||||||
|
s.expect(":testserver ERROR :Leaving the server").await?;
|
||||||
|
s.expect_eof().await?;
|
||||||
|
|
||||||
|
stream.shutdown().await?;
|
||||||
|
|
||||||
|
// wrap up
|
||||||
|
|
||||||
|
server.server.terminate().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
IRC SASL doc: https://ircv3.net/specs/extensions/sasl-3.1.html
|
||||||
|
AUTHENTICATE doc: https://modern.ircdocs.horse/#authenticate-message
|
||||||
|
*/
|
||||||
|
#[tokio::test]
|
||||||
|
async fn scenario_cap_full_negotiation() -> Result<()> {
|
||||||
|
let mut server = TestServer::start().await?;
|
||||||
|
|
||||||
|
// test scenario
|
||||||
|
|
||||||
|
server.storage.create_user("tester").await?;
|
||||||
|
server.storage.set_password("tester", "password").await?;
|
||||||
|
|
||||||
|
let mut stream = TcpStream::connect(server.server.addr).await?;
|
||||||
|
let mut s = TestScope::new(&mut stream);
|
||||||
|
|
||||||
|
s.send("CAP LS 302").await?;
|
||||||
|
s.send("NICK tester").await?;
|
||||||
|
s.send("USER UserName 0 * :Real Name").await?;
|
||||||
|
s.expect(":testserver CAP * LS :sasl=PLAIN").await?;
|
||||||
|
s.send("CAP REQ :sasl").await?;
|
||||||
|
s.expect(":testserver CAP tester ACK :sasl").await?;
|
||||||
|
s.send("AUTHENTICATE PLAIN").await?;
|
||||||
|
s.expect(":testserver AUTHENTICATE +").await?;
|
||||||
|
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
||||||
|
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.send("CAP END").await?;
|
||||||
|
|
||||||
|
s.expect(":testserver 001 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 004 tester testserver kek-0.1.alpha.3 r CFILPQbcefgijklmnopqrstvz").await?;
|
||||||
|
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
||||||
|
s.expect_nothing().await?;
|
||||||
|
s.send("QUIT :Leaving").await?;
|
||||||
|
s.expect(":testserver ERROR :Leaving the server").await?;
|
||||||
|
s.expect_eof().await?;
|
||||||
|
|
||||||
|
stream.shutdown().await?;
|
||||||
|
|
||||||
|
// wrap up
|
||||||
|
|
||||||
|
server.server.terminate().await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn scenario_cap_short_negotiation() -> Result<()> {
|
||||||
|
let mut server = TestServer::start().await?;
|
||||||
|
|
||||||
|
// test scenario
|
||||||
|
|
||||||
|
server.storage.create_user("tester").await?;
|
||||||
|
server.storage.set_password("tester", "password").await?;
|
||||||
|
|
||||||
|
let mut stream = TcpStream::connect(server.server.addr).await?;
|
||||||
|
let mut s = TestScope::new(&mut stream);
|
||||||
|
|
||||||
|
s.send("NICK tester").await?;
|
||||||
|
s.send("CAP REQ :sasl").await?;
|
||||||
|
s.send("USER UserName 0 * :Real Name").await?;
|
||||||
|
s.expect(":testserver CAP tester ACK :sasl").await?;
|
||||||
|
s.send("AUTHENTICATE PLAIN").await?;
|
||||||
|
s.expect(":testserver AUTHENTICATE +").await?;
|
||||||
|
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
||||||
|
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.send("CAP END").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?;
|
||||||
|
|
|
@ -13,6 +13,7 @@ prometheus.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
|
|
||||||
quick-xml.workspace = true
|
quick-xml.workspace = true
|
||||||
|
sasl.workspace = true
|
||||||
proto-xmpp = { path = "../proto-xmpp" }
|
proto-xmpp = { path = "../proto-xmpp" }
|
||||||
uuid = { version = "1.3.0", features = ["v4"] }
|
uuid = { version = "1.3.0", features = ["v4"] }
|
||||||
tokio-rustls = { version = "0.24.1", features = ["dangerous_configuration"] }
|
tokio-rustls = { version = "0.24.1", features = ["dangerous_configuration"] }
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
#![feature(generators, generator_trait, type_alias_impl_trait, impl_trait_in_assoc_type)]
|
#![feature(coroutines, coroutine_trait, type_alias_impl_trait, impl_trait_in_assoc_type)]
|
||||||
|
|
||||||
mod proto;
|
mod proto;
|
||||||
|
|
||||||
|
@ -28,9 +28,9 @@ use lavina_core::repo::Storage;
|
||||||
use lavina_core::room::RoomRegistry;
|
use lavina_core::room::RoomRegistry;
|
||||||
use lavina_core::terminator::Terminator;
|
use lavina_core::terminator::Terminator;
|
||||||
use proto_xmpp::bind::{Name, Resource};
|
use proto_xmpp::bind::{Name, Resource};
|
||||||
use proto_xmpp::sasl::AuthBody;
|
|
||||||
use proto_xmpp::stream::*;
|
use proto_xmpp::stream::*;
|
||||||
use proto_xmpp::xml::{Continuation, FromXml, Parser, ToXml};
|
use proto_xmpp::xml::{Continuation, FromXml, Parser, ToXml};
|
||||||
|
use sasl::AuthBody;
|
||||||
|
|
||||||
use self::proto::ClientPacket;
|
use self::proto::ClientPacket;
|
||||||
|
|
||||||
|
@ -249,9 +249,7 @@ async fn socket_auth(
|
||||||
read_xml_header(xml_reader, reader_buf).await?;
|
read_xml_header(xml_reader, reader_buf).await?;
|
||||||
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
||||||
|
|
||||||
xml_writer
|
xml_writer.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None))).await?;
|
||||||
.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None)))
|
|
||||||
.await?;
|
|
||||||
ServerStreamStart {
|
ServerStreamStart {
|
||||||
from: "localhost".into(),
|
from: "localhost".into(),
|
||||||
lang: "en".into(),
|
lang: "en".into(),
|
||||||
|
@ -317,9 +315,7 @@ async fn socket_final(
|
||||||
read_xml_header(xml_reader, reader_buf).await?;
|
read_xml_header(xml_reader, reader_buf).await?;
|
||||||
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
||||||
|
|
||||||
xml_writer
|
xml_writer.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None))).await?;
|
||||||
.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None)))
|
|
||||||
.await?;
|
|
||||||
ServerStreamStart {
|
ServerStreamStart {
|
||||||
from: "localhost".into(),
|
from: "localhost".into(),
|
||||||
lang: "en".into(),
|
lang: "en".into(),
|
||||||
|
|
|
@ -19,9 +19,7 @@ impl<'a> XmppConnection<'a> {
|
||||||
}) = m.to
|
}) = m.to
|
||||||
{
|
{
|
||||||
if server.0.as_ref() == "rooms.localhost" && m.r#type == MessageType::Groupchat {
|
if server.0.as_ref() == "rooms.localhost" && m.r#type == MessageType::Groupchat {
|
||||||
self.user_handle
|
self.user_handle.send_message(RoomId::from(name.0.clone())?, m.body.clone().into()).await?;
|
||||||
.send_message(RoomId::from(name.0.clone())?, m.body.clone().into())
|
|
||||||
.await?;
|
|
||||||
Message::<()> {
|
Message::<()> {
|
||||||
to: Some(Jid {
|
to: Some(Jid {
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
name: Some(self.user.xmpp_name.clone()),
|
||||||
|
|
|
@ -2,6 +2,7 @@ use super::*;
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use nom::combinator::{all_consuming, opt};
|
use nom::combinator::{all_consuming, opt};
|
||||||
|
use nonempty::NonEmpty;
|
||||||
|
|
||||||
/// Client-to-server command.
|
/// Client-to-server command.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
@ -59,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> {
|
||||||
|
@ -76,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),
|
||||||
|
@ -223,16 +226,29 @@ 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}
|
||||||
List { code: [u8; 3] },
|
List { code: [u8; 3] },
|
||||||
|
/// CAP REQ :...
|
||||||
|
Req(NonEmpty<CapReq>),
|
||||||
/// CAP END
|
/// CAP END
|
||||||
End,
|
End,
|
||||||
}
|
}
|
||||||
|
|
||||||
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> {
|
||||||
|
@ -247,14 +263,46 @@ 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))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct CapReq {
|
||||||
|
pub to_disable: bool,
|
||||||
|
pub name: Str,
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use assert_matches::*;
|
use assert_matches::*;
|
||||||
|
use nonempty::nonempty;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -324,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));
|
||||||
}
|
}
|
||||||
|
|
|
@ -66,6 +66,11 @@ pub enum ServerMessageBody {
|
||||||
Error {
|
Error {
|
||||||
reason: Str,
|
reason: Str,
|
||||||
},
|
},
|
||||||
|
Cap {
|
||||||
|
target: Str,
|
||||||
|
subcmd: CapSubBody,
|
||||||
|
},
|
||||||
|
Authenticate(Str),
|
||||||
N001Welcome {
|
N001Welcome {
|
||||||
client: Str,
|
client: Str,
|
||||||
text: Str,
|
text: Str,
|
||||||
|
@ -138,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 {
|
||||||
|
@ -181,6 +196,24 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b"ERROR :").await?;
|
writer.write_all(b"ERROR :").await?;
|
||||||
writer.write_all(reason.as_bytes()).await?;
|
writer.write_all(reason.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
|
ServerMessageBody::Cap { target, subcmd } => {
|
||||||
|
writer.write_all(b"CAP ").await?;
|
||||||
|
writer.write_all(target.as_bytes()).await?;
|
||||||
|
match subcmd {
|
||||||
|
CapSubBody::Ls(caps) => {
|
||||||
|
writer.write_all(b" LS :").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?;
|
||||||
|
@ -320,11 +353,33 @@ 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(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum CapSubBody {
|
||||||
|
Ls(Str),
|
||||||
|
Ack(Str),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum AwayStatus {
|
pub enum AwayStatus {
|
||||||
Here,
|
Here,
|
||||||
|
@ -336,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -361,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> {
|
||||||
|
@ -384,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::*;
|
||||||
|
@ -408,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());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -430,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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,7 +10,6 @@ regex.workspace = true
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
derive_more.workspace = true
|
derive_more.workspace = true
|
||||||
base64.workspace = true
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
assert_matches.workspace = true
|
assert_matches.workspace = true
|
||||||
|
|
|
@ -1,6 +1,6 @@
|
||||||
#![feature(
|
#![feature(
|
||||||
generators,
|
coroutines,
|
||||||
generator_trait,
|
coroutine_trait,
|
||||||
type_alias_impl_trait,
|
type_alias_impl_trait,
|
||||||
impl_trait_in_assoc_type
|
impl_trait_in_assoc_type
|
||||||
)]
|
)]
|
||||||
|
|
|
@ -1,14 +1,11 @@
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
|
|
||||||
use quick_xml::{
|
use anyhow::{anyhow, Result};
|
||||||
events::{BytesStart, Event},
|
use quick_xml::events::{BytesStart, Event};
|
||||||
NsReader, Writer,
|
use quick_xml::{NsReader, Writer};
|
||||||
};
|
|
||||||
use tokio::io::{AsyncBufRead, AsyncWrite};
|
use tokio::io::{AsyncBufRead, AsyncWrite};
|
||||||
use base64::{Engine as _, engine::general_purpose};
|
|
||||||
|
|
||||||
use super::skip_text;
|
use super::skip_text;
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
|
|
||||||
pub enum Mechanism {
|
pub enum Mechanism {
|
||||||
Plain,
|
Plain,
|
||||||
|
@ -29,98 +26,13 @@ impl Mechanism {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
|
||||||
pub struct AuthBody {
|
|
||||||
pub login: String,
|
|
||||||
pub password: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AuthBody {
|
|
||||||
pub fn from_str(input: &[u8]) -> Result<AuthBody> {
|
|
||||||
match general_purpose::STANDARD.decode(input){
|
|
||||||
Ok(decoded_body) => {
|
|
||||||
match String::from_utf8(decoded_body) {
|
|
||||||
Ok(parsed_to_string) => {
|
|
||||||
let separated_words: Vec<&str> = parsed_to_string.split("\x00").collect::<Vec<_>>().clone();
|
|
||||||
if separated_words.len() == 3 {
|
|
||||||
// first segment ignored (might be needed in the future)
|
|
||||||
Ok(AuthBody { login: separated_words[1].to_string(), password: separated_words[2].to_string() })
|
|
||||||
} else { return Err(anyhow!("Incorrect auth format")) }
|
|
||||||
},
|
|
||||||
Err(e) => return Err(anyhow!(e))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Err(e) => return Err(anyhow!(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
use super::*;
|
|
||||||
#[test]
|
|
||||||
fn test_returning_auth_body() {
|
|
||||||
let orig = b"\x00login\x00pass";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {login: "login".to_string(), password: "pass".to_string()};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(expected, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_ignoring_first_segment() {
|
|
||||||
let orig = b"ignored\x00login\x00pass";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {login: "login".to_string(), password: "pass".to_string()};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(expected, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_returning_auth_body_with_empty_strings() {
|
|
||||||
let orig = b"\x00\x00";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {login: "".to_string(), password: "".to_string()};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(expected, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_fail_if_size_less_then_3() {
|
|
||||||
let orig = b"login\x00pass";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {login: "login".to_string(), password: "pass".to_string()};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes());
|
|
||||||
|
|
||||||
assert!(result.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_fail_if_size_greater_then_3() {
|
|
||||||
let orig = b"first\x00login\x00pass\x00other";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {login: "login".to_string(), password: "pass".to_string()};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes());
|
|
||||||
|
|
||||||
assert!(result.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Auth {
|
pub struct Auth {
|
||||||
pub mechanism: Mechanism,
|
pub mechanism: Mechanism,
|
||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Auth {
|
impl Auth {
|
||||||
pub async fn parse(
|
pub async fn parse(reader: &mut NsReader<impl AsyncBufRead + Unpin>, buf: &mut Vec<u8>) -> Result<Auth> {
|
||||||
reader: &mut NsReader<impl AsyncBufRead + Unpin>,
|
|
||||||
buf: &mut Vec<u8>,
|
|
||||||
) -> Result<Auth> {
|
|
||||||
let event = skip_text!(reader, buf);
|
let event = skip_text!(reader, buf);
|
||||||
let mechanism = if let Event::Start(bytes) = event {
|
let mechanism = if let Event::Start(bytes) = event {
|
||||||
let mut mechanism = None;
|
let mut mechanism = None;
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
use std::ops::Generator;
|
use std::ops::Coroutine;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
|
||||||
use quick_xml::NsReader;
|
use quick_xml::NsReader;
|
||||||
|
@ -37,7 +37,7 @@ pub trait Parser: Sized {
|
||||||
|
|
||||||
impl<T, Out> Parser for T
|
impl<T, Out> Parser for T
|
||||||
where
|
where
|
||||||
T: Generator<(ResolveResult<'static>, &'static Event<'static>), Yield = (), Return = Out>
|
T: Coroutine<(ResolveResult<'static>, &'static Event<'static>), Yield = (), Return = Out>
|
||||||
+ Unpin,
|
+ Unpin,
|
||||||
{
|
{
|
||||||
type Output = Out;
|
type Output = Out;
|
||||||
|
@ -48,13 +48,13 @@ where
|
||||||
event: &Event<'a>,
|
event: &Event<'a>,
|
||||||
) -> Continuation<Self, Self::Output> {
|
) -> Continuation<Self, Self::Output> {
|
||||||
let s = Pin::new(&mut self);
|
let s = Pin::new(&mut self);
|
||||||
// this is a very rude workaround fixing the fact that rust generators
|
// this is a very rude workaround fixing the fact that rust coroutines
|
||||||
// 1. don't support higher-kinded lifetimes (i.e. no `impl for <'a> Generator<Event<'a>>)
|
// 1. don't support higher-kinded lifetimes (i.e. no `impl for <'a> Coroutine<Event<'a>>)
|
||||||
// 2. don't track borrows across yield points and lack thereof
|
// 2. don't track borrows across yield points and lack thereof
|
||||||
// implementors of Parser should manually check that inputs are not used across yields
|
// implementors of Parser should manually check that inputs are not used across yields
|
||||||
match s.resume(unsafe { std::mem::transmute((namespace, event)) }) {
|
match s.resume(unsafe { std::mem::transmute((namespace, event)) }) {
|
||||||
std::ops::GeneratorState::Yielded(()) => Continuation::Continue(self),
|
std::ops::CoroutineState::Yielded(()) => Continuation::Continue(self),
|
||||||
std::ops::GeneratorState::Complete(res) => Continuation::Final(res),
|
std::ops::CoroutineState::Complete(res) => Continuation::Final(res),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,8 @@
|
||||||
|
[package]
|
||||||
|
name = "sasl"
|
||||||
|
edition = "2021"
|
||||||
|
version.workspace = true
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow.workspace = true
|
||||||
|
base64.workspace = true
|
|
@ -0,0 +1,103 @@
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
use base64::engine::general_purpose;
|
||||||
|
use base64::Engine;
|
||||||
|
|
||||||
|
#[derive(PartialEq, Debug)]
|
||||||
|
pub struct AuthBody {
|
||||||
|
pub login: String,
|
||||||
|
pub password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthBody {
|
||||||
|
pub fn from_str(input: &[u8]) -> Result<AuthBody> {
|
||||||
|
match general_purpose::STANDARD.decode(input) {
|
||||||
|
Ok(decoded_body) => {
|
||||||
|
match String::from_utf8(decoded_body) {
|
||||||
|
Ok(parsed_to_string) => {
|
||||||
|
let separated_words: Vec<&str> = parsed_to_string.split("\x00").collect::<Vec<_>>().clone();
|
||||||
|
if separated_words.len() == 3 {
|
||||||
|
// first segment ignored (might be needed in the future)
|
||||||
|
Ok(AuthBody {
|
||||||
|
login: separated_words[1].to_string(),
|
||||||
|
password: separated_words[2].to_string(),
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
return Err(anyhow!("Incorrect auth format"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn test_returning_auth_body() {
|
||||||
|
let orig = b"\x00login\x00pass";
|
||||||
|
let encoded = general_purpose::STANDARD.encode(orig);
|
||||||
|
let expected = AuthBody {
|
||||||
|
login: "login".to_string(),
|
||||||
|
password: "pass".to_string(),
|
||||||
|
};
|
||||||
|
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_ignoring_first_segment() {
|
||||||
|
let orig = b"ignored\x00login\x00pass";
|
||||||
|
let encoded = general_purpose::STANDARD.encode(orig);
|
||||||
|
let expected = AuthBody {
|
||||||
|
login: "login".to_string(),
|
||||||
|
password: "pass".to_string(),
|
||||||
|
};
|
||||||
|
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_returning_auth_body_with_empty_strings() {
|
||||||
|
let orig = b"\x00\x00";
|
||||||
|
let encoded = general_purpose::STANDARD.encode(orig);
|
||||||
|
let expected = AuthBody {
|
||||||
|
login: "".to_string(),
|
||||||
|
password: "".to_string(),
|
||||||
|
};
|
||||||
|
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(expected, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fail_if_size_less_then_3() {
|
||||||
|
let orig = b"login\x00pass";
|
||||||
|
let encoded = general_purpose::STANDARD.encode(orig);
|
||||||
|
let expected = AuthBody {
|
||||||
|
login: "login".to_string(),
|
||||||
|
password: "pass".to_string(),
|
||||||
|
};
|
||||||
|
let result = AuthBody::from_str(encoded.as_bytes());
|
||||||
|
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_fail_if_size_greater_then_3() {
|
||||||
|
let orig = b"first\x00login\x00pass\x00other";
|
||||||
|
let encoded = general_purpose::STANDARD.encode(orig);
|
||||||
|
let expected = AuthBody {
|
||||||
|
login: "login".to_string(),
|
||||||
|
password: "pass".to_string(),
|
||||||
|
};
|
||||||
|
let result = AuthBody::from_str(encoded.as_bytes());
|
||||||
|
|
||||||
|
assert!(result.is_err());
|
||||||
|
}
|
||||||
|
}
|
|
@ -1 +1 @@
|
||||||
nightly-2023-10-06
|
nightly-2023-12-07
|
||||||
|
|
Loading…
Reference in New Issue