forked from lavina/lavina
1
0
Fork 0

Compare commits

...

6 Commits

Author SHA1 Message Date
Nikita Vilunov 80212fd3cc xmpp: make the hostname configurable 2024-04-15 02:27:34 +02:00
Nikita Vilunov d2600c4299 xmpp: add the server's hostname to the config 2024-04-15 02:27:10 +02:00
Nikita Vilunov 0944c449ca xmpp: in integration tests extract server startup code 2024-04-13 02:32:41 +02:00
Mikhail fd694cd75c Add message timestamps (#41)
Resolves #38

Reviewed-on: lavina/lavina#41
Co-authored-by: Mikhail <mikhail@liamets.dev>
Co-committed-by: Mikhail <mikhail@liamets.dev>
2024-04-12 21:32:21 +00:00
Nikita Vilunov cccc05afe9 xmpp: ignore text elements with spaces at the stream root 2024-04-11 23:08:09 +02:00
Nikita Vilunov 8b099f9be2 xmpp: fix handling of the `bind` iq 2024-04-07 12:06:23 +00:00
15 changed files with 273 additions and 159 deletions

21
.pre-commit-config.yaml Normal file
View File

@ -0,0 +1,21 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-toml
- id: end-of-file-fixer
- id: fix-byte-order-marker
- id: mixed-line-ending
- id: trailing-whitespace
- repo: local
hooks:
- id: fmt
name: fmt
description: Format
entry: cargo fmt
language: system
args:
- --all
types: [ rust ]
pass_filenames: false

68
Cargo.lock generated
View File

@ -45,6 +45,21 @@ version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5" checksum = "0942ffc6dcaadf03badf6e6a2d0228460359d5e34b57ccdc720b7382dfbd5ec5"
[[package]]
name = "android-tzdata"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0"
[[package]]
name = "android_system_properties"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "anstream" name = "anstream"
version = "0.6.13" version = "0.6.13"
@ -216,6 +231,20 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"wasm-bindgen",
"windows-targets 0.52.4",
]
[[package]] [[package]]
name = "clap" name = "clap"
version = "4.5.3" version = "4.5.3"
@ -274,6 +303,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "core-foundation-sys"
version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f"
[[package]] [[package]]
name = "cpufeatures" name = "cpufeatures"
version = "0.2.12" version = "0.2.12"
@ -729,6 +764,29 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "iana-time-zone"
version = "0.1.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141"
dependencies = [
"android_system_properties",
"core-foundation-sys",
"iana-time-zone-haiku",
"js-sys",
"wasm-bindgen",
"windows-core",
]
[[package]]
name = "iana-time-zone-haiku"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
dependencies = [
"cc",
]
[[package]] [[package]]
name = "idna" name = "idna"
version = "0.5.0" version = "0.5.0"
@ -818,6 +876,7 @@ name = "lavina-core"
version = "0.0.2-dev" version = "0.0.2-dev"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono",
"prometheus", "prometheus",
"serde", "serde",
"sqlx", "sqlx",
@ -2383,6 +2442,15 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
[[package]]
name = "windows-core"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9"
dependencies = [
"windows-targets 0.52.4",
]
[[package]] [[package]]
name = "windows-sys" name = "windows-sys"
version = "0.48.0" version = "0.48.0"

View File

@ -9,6 +9,7 @@ server_name = "irc.localhost"
listen_on = "127.0.0.1:5222" listen_on = "127.0.0.1:5222"
cert = "./certs/xmpp.pem" cert = "./certs/xmpp.pem"
key = "./certs/xmpp.key" key = "./certs/xmpp.key"
hostname = "localhost"
[storage] [storage]
db_path = "db.sqlite" db_path = "db.sqlite"

View File

@ -10,3 +10,4 @@ serde.workspace = true
tokio.workspace = true tokio.workspace = true
tracing.workspace = true tracing.workspace = true
prometheus.workspace = true prometheus.workspace = true
chrono = "0.4.37"

View File

@ -0,0 +1 @@
alter table messages add column created_at text;

View File

@ -87,14 +87,15 @@ impl Storage {
return Err(anyhow!("No such user")); return Err(anyhow!("No such user"));
}; };
sqlx::query( sqlx::query(
"insert into messages(room_id, id, content, author_id) "insert into messages(room_id, id, content, author_id, created_at)
values (?, ?, ?, ?); values (?, ?, ?, ?, ?);
update rooms set message_count = message_count + 1 where id = ?;", update rooms set message_count = message_count + 1 where id = ?;",
) )
.bind(room_id) .bind(room_id)
.bind(id) .bind(id)
.bind(content) .bind(content)
.bind(author_id) .bind(author_id)
.bind(chrono::Utc::now().to_string())
.bind(room_id) .bind(room_id)
.execute(&mut *executor) .execute(&mut *executor)
.await?; .await?;

View File

@ -24,9 +24,9 @@ impl<'a> XmppConnection<'a> {
to: None, to: None,
r#type: IqType::Result, r#type: IqType::Result,
body: BindResponse(Jid { body: BindResponse(Jid {
name: Some(Name("darova".into())), name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()), server: Server(self.hostname.clone()),
resource: Some(Resource("kek".into())), resource: Some(self.user.xmpp_resource.clone()),
}), }),
}; };
req.serialize(output); req.serialize(output);
@ -52,7 +52,7 @@ impl<'a> XmppConnection<'a> {
req.serialize(output); req.serialize(output);
} }
IqClientBody::DiscoInfo(info) => { IqClientBody::DiscoInfo(info) => {
let response = disco_info(iq.to.as_deref(), &info); let response = self.disco_info(iq.to.as_deref(), &info);
let req = Iq { let req = Iq {
from: iq.to, from: iq.to,
id: iq.id, id: iq.id,
@ -63,7 +63,7 @@ impl<'a> XmppConnection<'a> {
req.serialize(output); req.serialize(output);
} }
IqClientBody::DiscoItem(item) => { IqClientBody::DiscoItem(item) => {
let response = disco_items(iq.to.as_deref(), &item, self.rooms).await; let response = self.disco_items(iq.to.as_deref(), &item, self.rooms).await;
let req = Iq { let req = Iq {
from: iq.to, from: iq.to,
id: iq.id, id: iq.id,
@ -87,13 +87,13 @@ impl<'a> XmppConnection<'a> {
} }
} }
} }
}
fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery { fn disco_info(&self, to: Option<&str>, req: &InfoQuery) -> InfoQuery {
let identity; let identity;
let feature; let feature;
match to { match to {
Some("localhost") => { Some(r) if r == &*self.hostname => {
identity = vec![Identity { identity = vec![Identity {
category: "server".into(), category: "server".into(),
name: None, name: None,
@ -106,7 +106,7 @@ fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery {
Feature::new("presence"), Feature::new("presence"),
] ]
} }
Some("rooms.localhost") => { Some(r) if r == &*self.hostname_rooms => {
identity = vec![Identity { identity = vec![Identity {
category: "conference".into(), category: "conference".into(),
name: Some("Chat rooms".into()), name: Some("Chat rooms".into()),
@ -130,27 +130,27 @@ fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery {
} }
} }
async fn disco_items(to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery { async fn disco_items(&self, to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
let item = match to { let item = match to {
Some("localhost") => { Some(r) if r == &*self.hostname => {
vec![Item { vec![Item {
jid: Jid { jid: Jid {
name: None, name: None,
server: Server("rooms.localhost".into()), server: Server(self.hostname_rooms.clone()),
resource: None, resource: None,
}, },
name: None, name: None,
node: None, node: None,
}] }]
} }
Some("rooms.localhost") => { Some(r) if r == &*self.hostname_rooms => {
let room_list = rooms.get_all_rooms().await; let room_list = rooms.get_all_rooms().await;
room_list room_list
.into_iter() .into_iter()
.map(|room_info| Item { .map(|room_info| Item {
jid: Jid { jid: Jid {
name: Some(Name(room_info.id.into_inner())), name: Some(Name(room_info.id.into_inner())),
server: Server("rooms.localhost".into()), server: Server(self.hostname_rooms.clone()),
resource: None, resource: None,
}, },
name: None, name: None,
@ -162,3 +162,4 @@ async fn disco_items(to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) ->
}; };
ItemQuery { item } ItemQuery { item }
} }
}

View File

@ -9,7 +9,6 @@ use std::net::SocketAddr;
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use anyhow::anyhow;
use futures_util::future::join_all; use futures_util::future::join_all;
use prometheus::Registry as MetricsRegistry; use prometheus::Registry as MetricsRegistry;
use quick_xml::events::{BytesDecl, Event}; use quick_xml::events::{BytesDecl, Event};
@ -44,6 +43,7 @@ pub struct ServerConfig {
pub listen_on: SocketAddr, pub listen_on: SocketAddr,
pub cert: PathBuf, pub cert: PathBuf,
pub key: PathBuf, pub key: PathBuf,
pub hostname: Str,
} }
struct LoadedConfig { struct LoadedConfig {
@ -52,9 +52,17 @@ struct LoadedConfig {
} }
struct Authenticated { struct Authenticated {
/// Identifier of the authenticated player.
///
/// Used when communicating with lavina-core on behalf of the player.
player_id: PlayerId, player_id: PlayerId,
/// The user's XMPP name.
///
/// Used in `to` and `from` fields of XMPP messages.
xmpp_name: Name, xmpp_name: Name,
/// The resource given to this user by the server.
xmpp_resource: Resource, xmpp_resource: Resource,
/// The resource used by this user when joining MUCs.
xmpp_muc_name: Resource, xmpp_muc_name: Resource,
} }
@ -117,11 +125,12 @@ pub async fn launch(
let players = players.clone(); let players = players.clone();
let rooms = rooms.clone(); let rooms = rooms.clone();
let storage = storage.clone(); let storage = storage.clone();
let hostname = config.hostname.clone();
let terminator = Terminator::spawn(|termination| { let terminator = Terminator::spawn(|termination| {
let stopped_tx = stopped_tx.clone(); let stopped_tx = stopped_tx.clone();
let loaded_config = loaded_config.clone(); let loaded_config = loaded_config.clone();
async move { async move {
match handle_socket(loaded_config, stream, &socket_addr, players, rooms, storage, termination).await { match handle_socket(loaded_config, stream, &socket_addr, players, rooms, storage, hostname, termination).await {
Ok(_) => log::info!("Connection terminated"), Ok(_) => log::info!("Connection terminated"),
Err(err) => log::warn!("Connection failed: {err}"), Err(err) => log::warn!("Connection failed: {err}"),
} }
@ -156,12 +165,13 @@ pub async fn launch(
} }
async fn handle_socket( async fn handle_socket(
config: Arc<LoadedConfig>, cert_config: Arc<LoadedConfig>,
mut stream: TcpStream, mut stream: TcpStream,
socket_addr: &SocketAddr, socket_addr: &SocketAddr,
mut players: PlayerRegistry, mut players: PlayerRegistry,
rooms: RoomRegistry, rooms: RoomRegistry,
mut storage: Storage, mut storage: Storage,
hostname: Str,
termination: Deferred<()>, // TODO use it to stop the connection gracefully termination: Deferred<()>, // TODO use it to stop the connection gracefully
) -> Result<()> { ) -> Result<()> {
log::info!("Received an XMPP connection from {socket_addr}"); log::info!("Received an XMPP connection from {socket_addr}");
@ -170,12 +180,12 @@ async fn handle_socket(
let mut buf_reader = BufReader::new(reader); let mut buf_reader = BufReader::new(reader);
let mut buf_writer = BufWriter::new(writer); let mut buf_writer = BufWriter::new(writer);
socket_force_tls(&mut buf_reader, &mut buf_writer, &mut reader_buf).await?; socket_force_tls(&mut buf_reader, &mut buf_writer, &mut reader_buf, &hostname).await?;
let mut config = tokio_rustls::rustls::ServerConfig::builder() let mut config = tokio_rustls::rustls::ServerConfig::builder()
.with_safe_defaults() .with_safe_defaults()
.with_no_client_auth() .with_no_client_auth()
.with_single_cert(vec![config.cert.clone()], config.key.clone())?; .with_single_cert(vec![cert_config.cert.clone()], cert_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..."); log::debug!("Accepting TLS connection...");
@ -194,7 +204,7 @@ async fn handle_socket(
log::info!("Socket handling was terminated"); log::info!("Socket handling was terminated");
return Ok(()) return Ok(())
}, },
authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf, &mut storage) => { authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf, &mut storage, &hostname) => {
match authenticated { match authenticated {
Ok(authenticated) => { Ok(authenticated) => {
let mut connection = players.connect_to_player(authenticated.player_id.clone()).await; let mut connection = players.connect_to_player(authenticated.player_id.clone()).await;
@ -205,6 +215,7 @@ async fn handle_socket(
&authenticated, &authenticated,
&mut connection, &mut connection,
&rooms, &rooms,
&hostname,
) )
.await?; .await?;
}, },
@ -225,16 +236,18 @@ async fn socket_force_tls(
reader: &mut (impl AsyncBufRead + Unpin), reader: &mut (impl AsyncBufRead + Unpin),
writer: &mut (impl AsyncWrite + Unpin), writer: &mut (impl AsyncWrite + Unpin),
reader_buf: &mut Vec<u8>, reader_buf: &mut Vec<u8>,
hostname: &Str,
) -> Result<()> { ) -> Result<()> {
use proto_xmpp::tls::*; use proto_xmpp::tls::*;
let xml_reader = &mut NsReader::from_reader(reader); let xml_reader = &mut NsReader::from_reader(reader);
let xml_writer = &mut Writer::new(writer); let xml_writer = &mut Writer::new(writer);
// TODO validate the server hostname received in the stream start
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?; let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
let event = Event::Decl(BytesDecl::new("1.0", None, None)); let event = Event::Decl(BytesDecl::new("1.0", None, None));
xml_writer.write_event_async(event).await?; xml_writer.write_event_async(event).await?;
let msg = ServerStreamStart { let msg = ServerStreamStart {
from: "localhost".into(), from: hostname.to_string(),
lang: "en".into(), lang: "en".into(),
id: uuid::Uuid::new_v4().to_string(), id: uuid::Uuid::new_v4().to_string(),
version: "1.0".into(), version: "1.0".into(),
@ -259,12 +272,14 @@ async fn socket_auth(
xml_writer: &mut Writer<(impl AsyncWrite + Unpin)>, xml_writer: &mut Writer<(impl AsyncWrite + Unpin)>,
reader_buf: &mut Vec<u8>, reader_buf: &mut Vec<u8>,
storage: &mut Storage, storage: &mut Storage,
hostname: &Str,
) -> Result<Authenticated> { ) -> Result<Authenticated> {
// TODO validate the server hostname received in the stream start
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: hostname.to_string(),
lang: "en".into(), lang: "en".into(),
id: uuid::Uuid::new_v4().to_string(), id: uuid::Uuid::new_v4().to_string(),
version: "1.0".into(), version: "1.0".into(),
@ -307,11 +322,13 @@ async fn socket_auth(
return Err(fail("passwords do not match")); return Err(fail("passwords do not match"));
} }
let name: Str = name.as_str().into();
Ok(Authenticated { Ok(Authenticated {
player_id: PlayerId::from(name.as_str())?, player_id: PlayerId::from(name.clone())?,
xmpp_name: Name(name.to_string().into()), xmpp_name: Name(name.clone()),
xmpp_resource: Resource(name.to_string().into()), xmpp_resource: Resource(name.clone()),
xmpp_muc_name: Resource(name.to_string().into()), xmpp_muc_name: Resource(name.clone()),
}) })
} }
Err(e) => return Err(e), Err(e) => return Err(e),
@ -325,12 +342,14 @@ async fn socket_final(
authenticated: &Authenticated, authenticated: &Authenticated,
user_handle: &mut PlayerConnection, user_handle: &mut PlayerConnection,
rooms: &RoomRegistry, rooms: &RoomRegistry,
hostname: &Str,
) -> Result<()> { ) -> Result<()> {
// TODO validate the server hostname received in the stream start
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: hostname.to_string(),
lang: "en".into(), lang: "en".into(),
id: uuid::Uuid::new_v4().to_string(), id: uuid::Uuid::new_v4().to_string(),
version: "1.0".into(), version: "1.0".into(),
@ -356,13 +375,15 @@ async fn socket_final(
user: authenticated, user: authenticated,
user_handle, user_handle,
rooms, rooms,
hostname: hostname.clone(),
hostname_rooms: format!("rooms.{}", hostname).into(),
}; };
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: {
let (ns, event) = res?; let (ns, event) = res?;
if let Event::Text(ref e) = event { if let Event::Text(ref e) = event {
if e.iter().all(|x| *x == 0xA) { if e.iter().all(|x| *x == b'\n' || *x == b' ') {
break 's true; break 's true;
} }
} }
@ -412,6 +433,8 @@ struct XmppConnection<'a> {
user: &'a Authenticated, user: &'a Authenticated,
user_handle: &'a mut PlayerConnection, user_handle: &'a mut PlayerConnection,
rooms: &'a RoomRegistry, rooms: &'a RoomRegistry,
hostname: Str,
hostname_rooms: Str,
} }
impl<'a> XmppConnection<'a> { impl<'a> XmppConnection<'a> {

View File

@ -18,17 +18,17 @@ impl<'a> XmppConnection<'a> {
resource: _, resource: _,
}) = m.to }) = m.to
{ {
if server.0.as_ref() == "rooms.localhost" && m.r#type == MessageType::Groupchat { if server.0.as_ref() == &*self.hostname_rooms && m.r#type == MessageType::Groupchat {
self.user_handle.send_message(RoomId::from(name.0.clone())?, m.body.clone().into()).await?; self.user_handle.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()),
server: Server("localhost".into()), server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()), resource: Some(self.user.xmpp_resource.clone()),
}), }),
from: Some(Jid { from: Some(Jid {
name: Some(name), name: Some(name),
server: Server("rooms.localhost".into()), server: Server(self.hostname_rooms.clone()),
resource: Some(self.user.xmpp_muc_name.clone()), resource: Some(self.user.xmpp_muc_name.clone()),
}), }),
id: m.id, id: m.id,

View File

@ -16,12 +16,12 @@ impl<'a> XmppConnection<'a> {
Presence::<()> { Presence::<()> {
to: Some(Jid { to: Some(Jid {
name: Some(self.user.xmpp_name.clone()), name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()), server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()), resource: Some(self.user.xmpp_resource.clone()),
}), }),
from: Some(Jid { from: Some(Jid {
name: Some(self.user.xmpp_name.clone()), name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()), server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()), resource: Some(self.user.xmpp_resource.clone()),
}), }),
..Default::default() ..Default::default()
@ -36,12 +36,12 @@ impl<'a> XmppConnection<'a> {
Presence::<()> { Presence::<()> {
to: Some(Jid { to: Some(Jid {
name: Some(self.user.xmpp_name.clone()), name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()), server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()), resource: Some(self.user.xmpp_resource.clone()),
}), }),
from: Some(Jid { from: Some(Jid {
name: Some(name.clone()), name: Some(name.clone()),
server: Server("rooms.localhost".into()), server: Server(self.hostname_rooms.clone()),
resource: Some(self.user.xmpp_muc_name.clone()), resource: Some(self.user.xmpp_muc_name.clone()),
}), }),
..Default::default() ..Default::default()

View File

@ -21,12 +21,12 @@ impl<'a> XmppConnection<'a> {
Message::<()> { Message::<()> {
to: Some(Jid { to: Some(Jid {
name: Some(self.user.xmpp_name.clone()), name: Some(self.user.xmpp_name.clone()),
server: Server("localhost".into()), server: Server(self.hostname.clone()),
resource: Some(self.user.xmpp_resource.clone()), resource: Some(self.user.xmpp_resource.clone()),
}), }),
from: Some(Jid { from: Some(Jid {
name: Some(Name(room_id.into_inner().into())), name: Some(Name(room_id.into_inner().into())),
server: Server("rooms.localhost".into()), server: Server(self.hostname_rooms.clone()),
resource: Some(Resource(author_id.into_inner().into())), resource: Some(Resource(author_id.into_inner().into())),
}), }),
id: None, id: None,

View File

@ -1,5 +1,4 @@
use std::io::ErrorKind; use std::io::ErrorKind;
use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use std::time::Duration; use std::time::Duration;
@ -20,7 +19,7 @@ use tokio_rustls::TlsConnector;
use lavina_core::player::PlayerRegistry; use lavina_core::player::PlayerRegistry;
use lavina_core::repo::{Storage, StorageConfig}; use lavina_core::repo::{Storage, StorageConfig};
use lavina_core::room::RoomRegistry; use lavina_core::room::RoomRegistry;
use projection_xmpp::{launch, ServerConfig}; use projection_xmpp::{launch, RunningServer, ServerConfig};
use proto_xmpp::xml::{Continuation, FromXml, Parser}; use proto_xmpp::xml::{Continuation, FromXml, Parser};
pub async fn read_irc_message(reader: &mut BufReader<ReadHalf<'_>>, buf: &mut Vec<u8>) -> Result<usize> { pub async fn read_irc_message(reader: &mut BufReader<ReadHalf<'_>>, buf: &mut Vec<u8>) -> Result<usize> {
@ -122,9 +121,16 @@ impl ServerCertVerifier for IgnoreCertVerification {
} }
} }
#[tokio::test] struct TestServer {
async fn scenario_basic() -> Result<()> { metrics: MetricsRegistry,
tracing_subscriber::fmt::try_init(); storage: Storage,
rooms: RoomRegistry,
players: PlayerRegistry,
server: RunningServer,
}
impl 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(),
cert: "tests/certs/xmpp.pem".parse().unwrap(), cert: "tests/certs/xmpp.pem".parse().unwrap(),
@ -137,14 +143,27 @@ async fn scenario_basic() -> Result<()> {
.await?; .await?;
let rooms = RoomRegistry::new(&mut metrics, storage.clone()).unwrap(); let rooms = RoomRegistry::new(&mut metrics, storage.clone()).unwrap();
let players = PlayerRegistry::empty(rooms.clone(), &mut metrics).unwrap(); let players = PlayerRegistry::empty(rooms.clone(), &mut metrics).unwrap();
let server = launch(config, players, rooms, metrics, storage.clone()).await.unwrap(); let server = launch(config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await.unwrap();
Ok(TestServer {
metrics,
storage,
rooms,
players,
server,
})
}
}
#[tokio::test]
async fn scenario_basic() -> Result<()> {
let mut server = TestServer::start().await?;
// test scenario // test scenario
storage.create_user("tester").await?; server.storage.create_user("tester").await?;
storage.set_password("tester", "password").await?; server.storage.set_password("tester", "password").await?;
let mut stream = TcpStream::connect(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);
tracing::info!("TCP connection established"); tracing::info!("TCP connection established");
@ -169,7 +188,7 @@ async fn scenario_basic() -> Result<()> {
.with_no_client_auth(), .with_no_client_auth(),
)); ));
tracing::info!("Initiating TLS connection..."); tracing::info!("Initiating TLS connection...");
let mut stream = connector.connect(ServerName::IpAddress(server.addr.ip()), stream).await?; let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
tracing::info!("TLS connection established"); tracing::info!("TLS connection established");
let mut s = TestScopeTls::new(&mut stream, buffer); let mut s = TestScopeTls::new(&mut stream, buffer);
@ -183,33 +202,20 @@ async fn scenario_basic() -> Result<()> {
// wrap up // wrap up
server.terminate().await?; server.server.terminate().await?;
Ok(()) Ok(())
} }
#[tokio::test] #[tokio::test]
async fn scenario_basic_without_headers() -> Result<()> { async fn scenario_basic_without_headers() -> Result<()> {
tracing_subscriber::fmt::try_init(); let mut server = TestServer::start().await?;
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 // test scenario
storage.create_user("tester").await?; server.storage.create_user("tester").await?;
storage.set_password("tester", "password").await?; server.storage.set_password("tester", "password").await?;
let mut stream = TcpStream::connect(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);
tracing::info!("TCP connection established"); tracing::info!("TCP connection established");
@ -233,7 +239,7 @@ async fn scenario_basic_without_headers() -> Result<()> {
.with_no_client_auth(), .with_no_client_auth(),
)); ));
tracing::info!("Initiating TLS connection..."); tracing::info!("Initiating TLS connection...");
let mut stream = connector.connect(ServerName::IpAddress(server.addr.ip()), stream).await?; let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
tracing::info!("TLS connection established"); tracing::info!("TLS connection established");
let mut s = TestScopeTls::new(&mut stream, buffer); let mut s = TestScopeTls::new(&mut stream, buffer);
@ -246,33 +252,20 @@ async fn scenario_basic_without_headers() -> Result<()> {
// wrap up // wrap up
server.terminate().await?; server.server.terminate().await?;
Ok(()) Ok(())
} }
#[tokio::test] #[tokio::test]
async fn terminate_socket() -> Result<()> { async fn terminate_socket() -> Result<()> {
tracing_subscriber::fmt::try_init(); let mut server = TestServer::start().await?;
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();
let address: SocketAddr = ("127.0.0.1:0".parse().unwrap());
// test scenario // test scenario
storage.create_user("tester").await?; server.storage.create_user("tester").await?;
storage.set_password("tester", "password").await?; server.storage.set_password("tester", "password").await?;
let mut stream = TcpStream::connect(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);
tracing::info!("TCP connection established"); tracing::info!("TCP connection established");
@ -288,7 +281,6 @@ async fn terminate_socket() -> Result<()> {
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features")); assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
s.send(r#"<starttls/>"#).await?; s.send(r#"<starttls/>"#).await?;
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed")); assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
let buffer = s.buffer;
let connector = TlsConnector::from(Arc::new( let connector = TlsConnector::from(Arc::new(
ClientConfig::builder() ClientConfig::builder()
@ -298,10 +290,10 @@ async fn terminate_socket() -> Result<()> {
)); ));
tracing::info!("Initiating TLS connection..."); tracing::info!("Initiating TLS connection...");
let mut stream = connector.connect(ServerName::IpAddress(server.addr.ip()), stream).await?; let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
tracing::info!("TLS connection established"); tracing::info!("TLS connection established");
server.terminate().await?; server.server.terminate().await?;
assert_eq!(stream.read_u8().await.unwrap_err().kind(), ErrorKind::UnexpectedEof); assert_eq!(stream.read_u8().await.unwrap_err().kind(), ErrorKind::UnexpectedEof);

View File

@ -11,12 +11,15 @@ pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-bind";
// TODO remove `pub` in newtypes, introduce validation // TODO remove `pub` in newtypes, introduce validation
/// Name (node identifier) of an XMPP entity. Placed before the `@` in a JID.
#[derive(PartialEq, Eq, Debug, Clone)] #[derive(PartialEq, Eq, Debug, Clone)]
pub struct Name(pub Str); pub struct Name(pub Str);
/// Server name of an XMPP entity. Placed after the `@` and before the `/` in a JID.
#[derive(PartialEq, Eq, Debug, Clone)] #[derive(PartialEq, Eq, Debug, Clone)]
pub struct Server(pub Str); pub struct Server(pub Str);
/// Resource of an XMPP entity. Placed after the `/` in a JID.
#[derive(PartialEq, Eq, Debug, Clone)] #[derive(PartialEq, Eq, Debug, Clone)]
pub struct Resource(pub Str); pub struct Resource(pub Str);

View File

@ -8,11 +8,12 @@ Some useful commands for development and testing.
Following commands require `OpenSSL` to be installed. It is provided as `openssl` package in Arch Linux. Following commands require `OpenSSL` to be installed. It is provided as `openssl` package in Arch Linux.
Generate self-signed TLS certificate: Generate self-signed TLS certificate. Mind the common name (CN) field, it should match the domain name of the server.
Example for localhost:
openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -noenc \ openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -noenc \
-keyout certs/xmpp.key -out certs/xmpp.pem \ -keyout certs/xmpp.key -out certs/xmpp.pem \
-subj "/CN=example.com" -subj "/CN=localhost"
Print content of a TLS certificate: Print content of a TLS certificate:

View File

@ -19,6 +19,7 @@ server_name = "irc.localhost"
listen_on = "127.0.0.1:5222" listen_on = "127.0.0.1:5222"
cert = "./certs/xmpp.pem" cert = "./certs/xmpp.pem"
key = "./certs/xmpp.key" key = "./certs/xmpp.key"
hostname = "localhost"
[storage] [storage]
db_path = "db.sqlite" db_path = "db.sqlite"