forked from lavina/lavina
1
0
Fork 0

Compare commits

..

2 Commits

Author SHA1 Message Date
Nikita Vilunov ce3c49cff6 move sasl into separate crate 2023-10-13 16:54:08 +02:00
Nikita Vilunov dccb0b0f30 irc: sasl 2023-10-13 16:31:01 +02:00
12 changed files with 281 additions and 652 deletions

2
Cargo.lock generated
View File

@ -1279,7 +1279,6 @@ name = "projection-xmpp"
version = "0.0.2-dev" version = "0.0.2-dev"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"assert_matches",
"derive_more", "derive_more",
"futures-util", "futures-util",
"lavina-core", "lavina-core",
@ -1292,7 +1291,6 @@ dependencies = [
"tokio", "tokio",
"tokio-rustls", "tokio-rustls",
"tracing", "tracing",
"tracing-subscriber",
"uuid", "uuid",
] ]

View File

@ -29,7 +29,6 @@ tracing = "0.1.37" # logging & tracing api
prometheus = { version = "0.13.3", default-features = false } 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"
sasl = { path = "crates/sasl" } sasl = { path = "crates/sasl" }
[package] [package]
@ -47,7 +46,7 @@ serde.workspace = true
serde_json = "1.0.93" serde_json = "1.0.93"
tokio.workspace = true tokio.workspace = true
tracing.workspace = true tracing.workspace = true
tracing-subscriber.workspace = true tracing-subscriber = "0.3.16"
futures-util.workspace = true futures-util.workspace = true
prometheus.workspace = true prometheus.workspace = true
nonempty.workspace = true nonempty.workspace = true

View File

@ -16,10 +16,6 @@ quick-xml.workspace = true
sasl.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 = "0.24.1"
rustls-pemfile = "1.0.2" rustls-pemfile = "1.0.2"
derive_more.workspace = true derive_more.workspace = true
[dev-dependencies]
tracing-subscriber.workspace = true
assert_matches = "1.5.0"

View File

@ -1,2 +0,0 @@
max_width = 120
chain_width = 120

View File

@ -1,162 +0,0 @@
//! Handling of all client2server iq stanzas
use quick_xml::events::Event;
use lavina_core::room::RoomRegistry;
use proto_xmpp::bind::{BindResponse, Jid, Name, Resource, Server};
use proto_xmpp::client::{Iq, IqType};
use proto_xmpp::disco::{Feature, Identity, InfoQuery, Item, ItemQuery};
use proto_xmpp::roster::RosterQuery;
use proto_xmpp::session::Session;
use crate::proto::IqClientBody;
use crate::XmppConnection;
use proto_xmpp::xml::ToXml;
impl<'a> XmppConnection<'a> {
pub async fn handle_iq(&self, output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>) {
match iq.body {
IqClientBody::Bind(b) => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: IqType::Result,
body: BindResponse(Jid {
name: Some(Name("darova".into())),
server: Server("localhost".into()),
resource: Some(Resource("kek".into())),
}),
};
req.serialize(output);
}
IqClientBody::Session(_) => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: IqType::Result,
body: Session,
};
req.serialize(output);
}
IqClientBody::Roster(_) => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: IqType::Result,
body: RosterQuery,
};
req.serialize(output);
}
IqClientBody::DiscoInfo(info) => {
let response = disco_info(iq.to.as_deref(), &info);
let req = Iq {
from: iq.to,
id: iq.id,
to: None,
r#type: IqType::Result,
body: response,
};
req.serialize(output);
}
IqClientBody::DiscoItem(item) => {
let response = disco_items(iq.to.as_deref(), &item, self.rooms).await;
let req = Iq {
from: iq.to,
id: iq.id,
to: None,
r#type: IqType::Result,
body: response,
};
req.serialize(output);
}
_ => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: IqType::Error,
body: (),
};
req.serialize(output);
}
}
}
}
fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery {
let identity;
let feature;
match to {
Some("localhost") => {
identity = vec![Identity {
category: "server".into(),
name: None,
r#type: "im".into(),
}];
feature = vec![
Feature::new("http://jabber.org/protocol/disco#info"),
Feature::new("http://jabber.org/protocol/disco#items"),
Feature::new("iq"),
Feature::new("presence"),
]
}
Some("rooms.localhost") => {
identity = vec![Identity {
category: "conference".into(),
name: Some("Chat rooms".into()),
r#type: "text".into(),
}];
feature = vec![
Feature::new("http://jabber.org/protocol/disco#info"),
Feature::new("http://jabber.org/protocol/disco#items"),
Feature::new("http://jabber.org/protocol/muc"),
]
}
_ => {
identity = vec![];
feature = vec![];
}
};
InfoQuery {
node: None,
identity,
feature,
}
}
async fn disco_items(to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
let item = match to {
Some("localhost") => {
vec![Item {
jid: Jid {
name: None,
server: Server("rooms.localhost".into()),
resource: None,
},
name: None,
node: None,
}]
}
Some("rooms.localhost") => {
let room_list = rooms.get_all_rooms().await;
room_list
.into_iter()
.map(|room_info| Item {
jid: Jid {
name: Some(Name(room_info.id.into_inner())),
server: Server("rooms.localhost".into()),
resource: None,
},
name: None,
node: None,
})
.collect()
}
_ => vec![],
};
ItemQuery { item }
}

View File

@ -25,19 +25,18 @@ use tokio_rustls::TlsAcceptor;
use lavina_core::player::{PlayerConnection, PlayerId, PlayerRegistry}; use lavina_core::player::{PlayerConnection, PlayerId, PlayerRegistry};
use lavina_core::prelude::*; use lavina_core::prelude::*;
use lavina_core::repo::Storage; use lavina_core::repo::Storage;
use lavina_core::room::RoomRegistry; use lavina_core::room::{RoomId, RoomRegistry};
use lavina_core::terminator::Terminator; use lavina_core::terminator::Terminator;
use proto_xmpp::bind::{Name, Resource}; use proto_xmpp::bind::{BindResponse, Jid, Name, Resource, Server};
use proto_xmpp::client::{Iq, Message, MessageType, Presence};
use proto_xmpp::disco::*;
use proto_xmpp::roster::RosterQuery;
use proto_xmpp::session::Session;
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 sasl::AuthBody;
use self::proto::ClientPacket; use self::proto::{ClientPacket, IqClientBody};
mod iq;
mod message;
mod presence;
mod updates;
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct ServerConfig { pub struct ServerConfig {
@ -58,24 +57,13 @@ struct Authenticated {
xmpp_muc_name: Resource, xmpp_muc_name: Resource,
} }
pub struct RunningServer {
pub addr: SocketAddr,
terminator: Terminator,
}
impl RunningServer {
pub async fn terminate(self) -> Result<()> {
self.terminator.terminate().await
}
}
pub async fn launch( pub async fn launch(
config: ServerConfig, config: ServerConfig,
players: PlayerRegistry, players: PlayerRegistry,
rooms: RoomRegistry, rooms: RoomRegistry,
metrics: MetricsRegistry, metrics: MetricsRegistry,
storage: Storage, storage: Storage,
) -> Result<RunningServer> { ) -> Result<Terminator> {
log::info!("Starting XMPP projection"); log::info!("Starting XMPP projection");
let certs = certs(&mut SyncBufReader::new(File::open(config.cert)?))?; let certs = certs(&mut SyncBufReader::new(File::open(config.cert)?))?;
@ -92,8 +80,6 @@ pub async fn launch(
}); });
let listener = TcpListener::bind(config.listen_on).await?; let listener = TcpListener::bind(config.listen_on).await?;
let addr = listener.local_addr()?;
let terminator = Terminator::spawn(|mut termination| async move { let terminator = Terminator::spawn(|mut termination| async move {
let (stopped_tx, mut stopped_rx) = channel(32); let (stopped_tx, mut stopped_rx) = channel(32);
let mut actors = HashMap::new(); let mut actors = HashMap::new();
@ -152,7 +138,7 @@ pub async fn launch(
Ok(()) Ok(())
}); });
log::info!("Started XMPP projection"); log::info!("Started XMPP projection");
Ok(RunningServer { addr, terminator }) Ok(terminator)
} }
async fn handle_socket( async fn handle_socket(
@ -178,7 +164,6 @@ async fn handle_socket(
.with_single_cert(vec![config.cert.clone()], config.key.clone())?; .with_single_cert(vec![config.cert.clone()], config.key.clone())?;
config.key_log = Arc::new(tokio_rustls::rustls::KeyLogFile::new()); config.key_log = Arc::new(tokio_rustls::rustls::KeyLogFile::new());
log::debug!("Accepting TLS connection...");
let acceptor = TlsAcceptor::from(Arc::new(config)); let acceptor = TlsAcceptor::from(Arc::new(config));
let new_stream = acceptor.accept(stream).await?; let new_stream = acceptor.accept(stream).await?;
log::debug!("TLS connection established"); log::debug!("TLS connection established");
@ -249,7 +234,9 @@ 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.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None))).await?; xml_writer
.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(),
@ -315,7 +302,9 @@ 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.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None))).await?; xml_writer
.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(),
@ -339,11 +328,6 @@ async fn socket_final(
let mut next_xml_event = Box::pin(xml_reader.read_resolved_event_into_async(reader_buf)); let mut next_xml_event = Box::pin(xml_reader.read_resolved_event_into_async(reader_buf));
'outer: loop { 'outer: loop {
let mut conn = XmppConnection {
user: authenticated,
user_handle,
rooms,
};
let should_recreate_xml_future = select! { let should_recreate_xml_future = select! {
biased; biased;
res = &mut next_xml_event => 's: { res = &mut next_xml_event => 's: {
@ -356,7 +340,7 @@ async fn socket_final(
match parser.consume(ns, &event) { match parser.consume(ns, &event) {
Continuation::Final(res) => { Continuation::Final(res) => {
let res = res?; let res = res?;
let stop = conn.handle_packet(&mut events, res).await?; let stop = handle_packet(&mut events, res, authenticated, user_handle, rooms).await?;
for i in &events { for i in &events {
xml_writer.write_event_async(i).await?; xml_writer.write_event_async(i).await?;
} }
@ -371,9 +355,32 @@ async fn socket_final(
} }
true true
}, },
update = conn.user_handle.receiver.recv() => { update = user_handle.receiver.recv() => {
if let Some(update) = update { if let Some(update) = update {
conn.handle_update(&mut events, update).await?; match update {
lavina_core::player::Updates::NewMessage { room_id, author_id, body } => {
Message::<()> {
to: Some(Jid {
name: Some(authenticated.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(authenticated.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(Name(room_id.into_inner().into())),
server: Server("rooms.localhost".into()),
resource: Some(Resource(author_id.into_inner().into())),
}),
id: None,
r#type: proto_xmpp::client::MessageType::Groupchat,
lang: None,
subject: None,
body: body.into(),
custom: vec![],
}
.serialize(&mut events);
}
_ => {},
}
for i in &events { for i in &events {
xml_writer.write_event_async(i).await?; xml_writer.write_event_async(i).await?;
} }
@ -395,34 +402,247 @@ async fn socket_final(
Ok(()) Ok(())
} }
struct XmppConnection<'a> { async fn handle_packet(
user: &'a Authenticated, output: &mut Vec<Event<'static>>,
user_handle: &'a mut PlayerConnection, packet: ClientPacket,
rooms: &'a RoomRegistry, user: &Authenticated,
} user_handle: &mut PlayerConnection,
rooms: &RoomRegistry,
impl<'a> XmppConnection<'a> { ) -> Result<bool> {
async fn handle_packet(&mut self, output: &mut Vec<Event<'static>>, packet: ClientPacket) -> Result<bool> { Ok(match packet {
let res = match packet {
proto::ClientPacket::Iq(iq) => { proto::ClientPacket::Iq(iq) => {
self.handle_iq(output, iq).await; handle_iq(output, iq, rooms).await;
false false
} }
ClientPacket::Message(m) => { proto::ClientPacket::Message(m) => {
self.handle_message(output, m).await?; if let Some(Jid {
name: Some(name),
server,
resource: _,
}) = m.to
{
if server.0.as_ref() == "rooms.localhost" && m.r#type == MessageType::Groupchat {
user_handle
.send_message(RoomId::from(name.0.clone())?, m.body.clone().into())
.await?;
Message::<()> {
to: Some(Jid {
name: Some(user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(name),
server: Server("rooms.localhost".into()),
resource: Some(user.xmpp_muc_name.clone()),
}),
id: m.id,
r#type: proto_xmpp::client::MessageType::Groupchat,
lang: None,
subject: None,
body: m.body.clone(),
custom: vec![],
}
.serialize(output);
false false
} else {
todo!()
}
} else {
todo!()
}
} }
proto::ClientPacket::Presence(p) => { proto::ClientPacket::Presence(p) => {
self.handle_presence(output, p).await?; let response = if p.to.is_none() {
Presence::<()> {
to: Some(Jid {
name: Some(user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(user.xmpp_resource.clone()),
}),
..Default::default()
}
} else if let Some(Jid {
name: Some(name),
server,
resource: Some(resource),
}) = p.to
{
let a = user_handle.join_room(RoomId::from(name.0.clone())?).await?;
Presence::<()> {
to: Some(Jid {
name: Some(user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(name.clone()),
server: Server("rooms.localhost".into()),
resource: Some(user.xmpp_muc_name.clone()),
}),
..Default::default()
}
} else {
Presence::<()>::default()
};
response.serialize(output);
false false
} }
proto::ClientPacket::StreamEnd => { proto::ClientPacket::StreamEnd => {
ServerStreamEnd.serialize(output); ServerStreamEnd.serialize(output);
true true
} }
})
}
async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms: &RoomRegistry) {
match iq.body {
proto::IqClientBody::Bind(b) => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: proto_xmpp::client::IqType::Result,
body: BindResponse(Jid {
name: Some(Name("darova".into())),
server: Server("localhost".into()),
resource: Some(Resource("kek".into())),
}),
}; };
Ok(res) req.serialize(output);
} }
proto::IqClientBody::Session(_) => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: proto_xmpp::client::IqType::Result,
body: Session,
};
req.serialize(output);
}
proto::IqClientBody::Roster(_) => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: proto_xmpp::client::IqType::Result,
body: RosterQuery,
};
req.serialize(output);
}
proto::IqClientBody::DiscoInfo(info) => {
let response = disco_info(iq.to.as_deref(), &info);
let req = Iq {
from: iq.to,
id: iq.id,
to: None,
r#type: proto_xmpp::client::IqType::Result,
body: response,
};
req.serialize(output);
}
proto::IqClientBody::DiscoItem(item) => {
let response = disco_items(iq.to.as_deref(), &item, rooms).await;
let req = Iq {
from: iq.to,
id: iq.id,
to: None,
r#type: proto_xmpp::client::IqType::Result,
body: response,
};
req.serialize(output);
}
_ => {
let req = Iq {
from: None,
id: iq.id,
to: None,
r#type: proto_xmpp::client::IqType::Error,
body: (),
};
req.serialize(output);
}
}
}
fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery {
let identity;
let feature;
match to {
Some("localhost") => {
identity = vec![Identity {
category: "server".into(),
name: None,
r#type: "im".into(),
}];
feature = vec![
Feature::new("http://jabber.org/protocol/disco#info"),
Feature::new("http://jabber.org/protocol/disco#items"),
Feature::new("iq"),
Feature::new("presence"),
]
}
Some("rooms.localhost") => {
identity = vec![Identity {
category: "conference".into(),
name: Some("Chat rooms".into()),
r#type: "text".into(),
}];
feature = vec![
Feature::new("http://jabber.org/protocol/disco#info"),
Feature::new("http://jabber.org/protocol/disco#items"),
Feature::new("http://jabber.org/protocol/muc"),
]
}
_ => {
identity = vec![];
feature = vec![];
}
};
InfoQuery {
node: None,
identity,
feature,
}
}
async fn disco_items(to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
let item = match to {
Some("localhost") => {
vec![Item {
jid: Jid {
name: None,
server: Server("rooms.localhost".into()),
resource: None,
},
name: None,
node: None,
}]
}
Some("rooms.localhost") => {
let room_list = rooms.get_all_rooms().await;
room_list
.into_iter()
.map(|room_info| Item {
jid: Jid {
name: Some(Name(room_info.id.into_inner())),
server: Server("rooms.localhost".into()),
resource: None,
},
name: None,
node: None,
})
.collect()
}
_ => vec![],
};
ItemQuery { item }
} }
async fn read_xml_header( async fn read_xml_header(

View File

@ -1,52 +0,0 @@
//! Handling of all client2server message stanzas
use quick_xml::events::Event;
use lavina_core::prelude::*;
use lavina_core::room::RoomId;
use proto_xmpp::bind::{Jid, Server};
use proto_xmpp::client::{Message, MessageType};
use proto_xmpp::xml::{Ignore, ToXml};
use crate::XmppConnection;
impl<'a> XmppConnection<'a> {
pub async fn handle_message(&mut self, output: &mut Vec<Event<'static>>, m: Message<Ignore>) -> Result<()> {
if let Some(Jid {
name: Some(name),
server,
resource: _,
}) = m.to
{
if server.0.as_ref() == "rooms.localhost" && m.r#type == MessageType::Groupchat {
self.user_handle
.send_message(RoomId::from(name.0.clone())?, m.body.clone().into())
.await?;
Message::<()> {
to: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(self.user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(name),
server: Server("rooms.localhost".into()),
resource: Some(self.user.xmpp_muc_name.clone()),
}),
id: m.id,
r#type: MessageType::Groupchat,
lang: None,
subject: None,
body: m.body.clone(),
custom: vec![],
}
.serialize(output);
Ok(())
} else {
todo!()
}
} else {
todo!()
}
}
}

View File

@ -1,55 +0,0 @@
//! Handling of all client2server presence stanzas
use quick_xml::events::Event;
use lavina_core::prelude::*;
use lavina_core::room::RoomId;
use proto_xmpp::bind::{Jid, Server};
use proto_xmpp::client::Presence;
use proto_xmpp::xml::{Ignore, ToXml};
use crate::XmppConnection;
impl<'a> XmppConnection<'a> {
pub async fn handle_presence(&mut self, output: &mut Vec<Event<'static>>, p: Presence<Ignore>) -> Result<()> {
let response = if p.to.is_none() {
Presence::<()> {
to: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(self.user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(self.user.xmpp_resource.clone()),
}),
..Default::default()
}
} else if let Some(Jid {
name: Some(name),
server,
resource: Some(resource),
}) = p.to
{
let a = self.user_handle.join_room(RoomId::from(name.0.clone())?).await?;
Presence::<()> {
to: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(self.user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(name.clone()),
server: Server("rooms.localhost".into()),
resource: Some(self.user.xmpp_muc_name.clone()),
}),
..Default::default()
}
} else {
Presence::<()>::default()
};
response.serialize(output);
Ok(())
}
}

View File

@ -1,45 +0,0 @@
//! Handling of updates and converting them into server2client stanzas
use anyhow::Result;
use quick_xml::events::Event;
use lavina_core::player::Updates;
use proto_xmpp::bind::{Jid, Name, Resource, Server};
use proto_xmpp::client::{Message, MessageType};
use proto_xmpp::xml::ToXml;
use crate::XmppConnection;
impl<'a> XmppConnection<'a> {
pub async fn handle_update(&mut self, output: &mut Vec<Event<'static>>, update: Updates) -> Result<()> {
match update {
Updates::NewMessage {
room_id,
author_id,
body,
} => {
Message::<()> {
to: Some(Jid {
name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()),
resource: Some(self.user.xmpp_resource.clone()),
}),
from: Some(Jid {
name: Some(Name(room_id.into_inner().into())),
server: Server("rooms.localhost".into()),
resource: Some(Resource(author_id.into_inner().into())),
}),
id: None,
r#type: MessageType::Groupchat,
lang: None,
subject: None,
body: body.into(),
custom: vec![],
}
.serialize(output);
}
_ => {}
}
Ok(())
}
}

View File

@ -1,52 +0,0 @@
-----BEGIN PRIVATE KEY-----
MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCuViBTGN8tMaQ8
G8zixL7duElTFCuP6wQhmDsX8ut4V3eEshUpDIIFkCSX17hzfI7duBp1pe7Ket+F
z5XjbV+ruvxpawvsCgsfGrwXE1vaD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EFlwJHacPU6mVUUnXLwZIt0VWB3RUT9bgbkXFfkg7Qrccl7Blc0458l8wd2
mvNgdEGG9Z8VhyaExAHerpOD299llaDTcV+jKLLAboXzDGJsPmMfRu2DWwosfYQJ
MIKajyylmGOrAk+8fVTVWOPJBE6AmxDpKtZQO04nQq78PohP/CsibalimOf00Wqb
2x05ssWFP71lmdGilaXCp/mkhaVz/G7ZuDSY9AxCPH4+3pTUbMgsfEmLXRTrUo9c
B4zz0eDoUiqU9I4TWAHGhnn7b2e6o8ko0baq+PaCSCDK8haL/17CUyMYQBBdhlG6
sSR2IBSXkxGQZnhfmQdYwc7Y3IgsJJoN0ZfqnyBY+u/ZOBegcZFuhMiDGILJBgFi
QmgQFTozXKkeEzFdWoRn57lgcBABcMHSucnjekk80uLIWIlL36IyYkPbeI6/I0/l
ajKftsVEY96hYUXtDBykBpg6gsJXj2gP2FXHW7ngtuI4/mOqI3ltcWh1C83MvM5N
zMYfTNtxVM1vyvN1M7b7iMeosvmAIvQE3bFk/pJCHAZPfsu0zmeizPHBgCySygLn
JQ==
-----END CERTIFICATE-----

View File

@ -1,186 +0,0 @@
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use assert_matches::*;
use prometheus::Registry as MetricsRegistry;
use quick_xml::events::Event;
use quick_xml::NsReader;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::io::{ReadHalf as GenericReadHalf, WriteHalf as GenericWriteHalf};
use tokio::net::tcp::{ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio_rustls::client::TlsStream;
use tokio_rustls::rustls::client::ServerCertVerifier;
use tokio_rustls::rustls::{ClientConfig, ServerName};
use tokio_rustls::TlsConnector;
use lavina_core::player::PlayerRegistry;
use lavina_core::repo::{Storage, StorageConfig};
use lavina_core::room::RoomRegistry;
use projection_xmpp::{launch, ServerConfig};
use proto_xmpp::xml::{Continuation, FromXml, Parser};
pub async fn read_irc_message(reader: &mut BufReader<ReadHalf<'_>>, buf: &mut Vec<u8>) -> Result<usize> {
let mut size = 0;
let res = reader.read_until(b'\n', buf).await?;
size += res;
return Ok(size);
}
struct TestScope<'a> {
reader: NsReader<BufReader<ReadHalf<'a>>>,
writer: WriteHalf<'a>,
buffer: Vec<u8>,
}
impl<'a> TestScope<'a> {
fn new(stream: &mut TcpStream) -> TestScope<'_> {
let (reader, writer) = stream.split();
let reader = NsReader::from_reader(BufReader::new(reader));
let buffer = vec![];
TestScope { reader, writer, buffer }
}
async fn send(&mut self, str: &str) -> Result<()> {
self.writer.write_all(str.as_bytes()).await?;
self.writer.flush().await?;
Ok(())
}
async fn next_xml_event(&mut self) -> Result<Event<'_>> {
self.buffer.clear();
let event = self.reader.read_event_into_async(&mut self.buffer).await?;
Ok(event)
}
async fn read<T: FromXml>(&mut self) -> Result<T> {
self.buffer.clear();
let (ns, event) = self.reader.read_resolved_event_into_async(&mut self.buffer).await?;
let mut parser: Continuation<_, std::result::Result<T, anyhow::Error>> = T::parse().consume(ns, &event);
loop {
match parser {
Continuation::Final(res) => return Ok(res?),
Continuation::Continue(next) => {
let (ns, event) = self.reader.read_resolved_event_into_async(&mut self.buffer).await?;
parser = next.consume(ns, &event);
}
}
}
}
}
struct TestScopeTls<'a> {
reader: NsReader<BufReader<GenericReadHalf<&'a mut TlsStream<TcpStream>>>>,
writer: GenericWriteHalf<&'a mut TlsStream<TcpStream>>,
buffer: Vec<u8>,
pub timeout: Duration,
}
impl<'a> TestScopeTls<'a> {
fn new(stream: &'a mut TlsStream<TcpStream>, buffer: Vec<u8>) -> TestScopeTls<'a> {
let (reader, writer) = tokio::io::split(stream);
let reader = NsReader::from_reader(BufReader::new(reader));
let timeout = Duration::from_millis(100);
TestScopeTls {
reader,
writer,
buffer,
timeout,
}
}
async fn send(&mut self, str: &str) -> Result<()> {
self.writer.write_all(str.as_bytes()).await?;
self.writer.flush().await?;
Ok(())
}
async fn next_xml_event(&mut self) -> Result<Event<'_>> {
self.buffer.clear();
let event = self.reader.read_event_into_async(&mut self.buffer);
let event = tokio::time::timeout(self.timeout, event).await??;
Ok(event)
}
}
struct IgnoreCertVerification;
impl ServerCertVerifier for IgnoreCertVerification {
fn verify_server_cert(
&self,
_end_entity: &tokio_rustls::rustls::Certificate,
_intermediates: &[tokio_rustls::rustls::Certificate],
_server_name: &ServerName,
_scts: &mut dyn Iterator<Item = &[u8]>,
_ocsp_response: &[u8],
_now: std::time::SystemTime,
) -> std::result::Result<tokio_rustls::rustls::client::ServerCertVerified, tokio_rustls::rustls::Error> {
Ok(tokio_rustls::rustls::client::ServerCertVerified::assertion())
}
}
#[tokio::test]
async fn scenario_basic() -> Result<()> {
tracing_subscriber::fmt::init();
let config = ServerConfig {
listen_on: "127.0.0.1:0".parse().unwrap(),
cert: "tests/certs/xmpp.pem".parse().unwrap(),
key: "tests/certs/xmpp.key".parse().unwrap(),
};
let mut metrics = MetricsRegistry::new();
let mut storage = Storage::open(StorageConfig {
db_path: ":memory:".into(),
})
.await?;
let rooms = RoomRegistry::new(&mut metrics, storage.clone()).unwrap();
let players = PlayerRegistry::empty(rooms.clone(), &mut metrics).unwrap();
let server = launch(config, players, rooms, metrics, storage.clone()).await.unwrap();
// test scenario
storage.create_user("tester").await?;
storage.set_password("tester", "password").await?;
let mut stream = TcpStream::connect(server.addr).await?;
let mut s = TestScope::new(&mut stream);
tracing::info!("TCP connection established");
s.send(r#"<?xml version="1.0"?>"#).await?;
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"required"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
s.send(r#"<starttls/>"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
let buffer = s.buffer;
tracing::info!("TLS feature negotiation complete");
let connector = TlsConnector::from(Arc::new(
ClientConfig::builder()
.with_safe_defaults()
.with_custom_certificate_verifier(Arc::new(IgnoreCertVerification))
.with_no_client_auth(),
));
tracing::info!("Initiating TLS connection...");
let mut stream = connector.connect(ServerName::IpAddress(server.addr.ip()), stream).await?;
tracing::info!("TLS connection established");
let mut s = TestScopeTls::new(&mut stream, buffer);
s.send(r#"<?xml version="1.0"?>"#).await?;
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
stream.shutdown().await?;
// wrap up
server.terminate().await?;
Ok(())
}