forked from lavina/lavina
Compare commits
No commits in common. "e6633477a1f79fbb1b63650514b4d2846f534549" and "36b0d50d5103f6bd86ef52680ce7f001ae3b1d7d" have entirely different histories.
e6633477a1
...
36b0d50d51
|
@ -1,21 +0,0 @@
|
||||||
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
|
|
|
@ -45,21 +45,6 @@ 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"
|
||||||
|
@ -231,20 +216,6 @@ 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"
|
||||||
|
@ -303,12 +274,6 @@ 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"
|
||||||
|
@ -764,29 +729,6 @@ 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"
|
||||||
|
@ -876,7 +818,6 @@ name = "lavina-core"
|
||||||
version = "0.0.2-dev"
|
version = "0.0.2-dev"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
|
||||||
"prometheus",
|
"prometheus",
|
||||||
"serde",
|
"serde",
|
||||||
"sqlx",
|
"sqlx",
|
||||||
|
@ -2442,15 +2383,6 @@ 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"
|
||||||
|
|
|
@ -9,7 +9,6 @@ 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"
|
||||||
|
|
|
@ -10,4 +10,3 @@ 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"
|
|
||||||
|
|
|
@ -1 +0,0 @@
|
||||||
alter table messages add column created_at text;
|
|
|
@ -7,16 +7,16 @@
|
||||||
//!
|
//!
|
||||||
//! A player actor is a serial handler of commands from a single player. It is preferable to run all per-player validations in the player actor,
|
//! A player actor is a serial handler of commands from a single player. It is preferable to run all per-player validations in the player actor,
|
||||||
//! so that they don't overload the room actor.
|
//! so that they don't overload the room actor.
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::{
|
||||||
use std::sync::Arc;
|
collections::{HashMap, HashSet},
|
||||||
|
sync::{Arc, RwLock},
|
||||||
|
};
|
||||||
|
|
||||||
use prometheus::{IntGauge, Registry as MetricsRegistry};
|
use prometheus::{IntGauge, Registry as MetricsRegistry};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tokio::sync::mpsc::{channel, Receiver, Sender};
|
use tokio::sync::mpsc::{channel, Receiver, Sender};
|
||||||
use tokio::sync::RwLock;
|
|
||||||
|
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::repo::Storage;
|
|
||||||
use crate::room::{RoomHandle, RoomId, RoomInfo, RoomRegistry};
|
use crate::room::{RoomHandle, RoomId, RoomInfo, RoomRegistry};
|
||||||
use crate::table::{AnonTable, Key as AnonKey};
|
use crate::table::{AnonTable, Key as AnonKey};
|
||||||
|
|
||||||
|
@ -208,41 +208,36 @@ pub enum Updates {
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct PlayerRegistry(Arc<RwLock<PlayerRegistryInner>>);
|
pub struct PlayerRegistry(Arc<RwLock<PlayerRegistryInner>>);
|
||||||
impl PlayerRegistry {
|
impl PlayerRegistry {
|
||||||
pub fn empty(
|
pub fn empty(room_registry: RoomRegistry, metrics: &mut MetricsRegistry) -> Result<PlayerRegistry> {
|
||||||
room_registry: RoomRegistry,
|
|
||||||
storage: Storage,
|
|
||||||
metrics: &mut MetricsRegistry,
|
|
||||||
) -> Result<PlayerRegistry> {
|
|
||||||
let metric_active_players = IntGauge::new("chat_players_active", "Number of alive player actors")?;
|
let metric_active_players = IntGauge::new("chat_players_active", "Number of alive player actors")?;
|
||||||
metrics.register(Box::new(metric_active_players.clone()))?;
|
metrics.register(Box::new(metric_active_players.clone()))?;
|
||||||
let inner = PlayerRegistryInner {
|
let inner = PlayerRegistryInner {
|
||||||
room_registry,
|
room_registry,
|
||||||
storage,
|
|
||||||
players: HashMap::new(),
|
players: HashMap::new(),
|
||||||
metric_active_players,
|
metric_active_players,
|
||||||
};
|
};
|
||||||
Ok(PlayerRegistry(Arc::new(RwLock::new(inner))))
|
Ok(PlayerRegistry(Arc::new(RwLock::new(inner))))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_or_launch_player(&mut self, id: &PlayerId) -> PlayerHandle {
|
pub async fn get_or_create_player(&mut self, id: PlayerId) -> PlayerHandle {
|
||||||
let mut inner = self.0.write().await;
|
let mut inner = self.0.write().unwrap();
|
||||||
if let Some((handle, _)) = inner.players.get(id) {
|
if let Some((handle, _)) = inner.players.get(&id) {
|
||||||
handle.clone()
|
handle.clone()
|
||||||
} else {
|
} else {
|
||||||
let (handle, fiber) = Player::launch(id.clone(), inner.room_registry.clone(), inner.storage.clone()).await;
|
let (handle, fiber) = Player::launch(id.clone(), inner.room_registry.clone());
|
||||||
inner.players.insert(id.clone(), (handle.clone(), fiber));
|
inner.players.insert(id, (handle.clone(), fiber));
|
||||||
inner.metric_active_players.inc();
|
inner.metric_active_players.inc();
|
||||||
handle
|
handle
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn connect_to_player(&mut self, id: &PlayerId) -> PlayerConnection {
|
pub async fn connect_to_player(&mut self, id: PlayerId) -> PlayerConnection {
|
||||||
let player_handle = self.get_or_launch_player(id).await;
|
let player_handle = self.get_or_create_player(id).await;
|
||||||
player_handle.subscribe().await
|
player_handle.subscribe().await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn shutdown_all(&mut self) -> Result<()> {
|
pub async fn shutdown_all(&mut self) -> Result<()> {
|
||||||
let mut inner = self.0.write().await;
|
let mut inner = self.0.write().unwrap();
|
||||||
for (i, (k, j)) in inner.players.drain() {
|
for (i, (k, j)) in inner.players.drain() {
|
||||||
k.send(ActorCommand::Stop).await;
|
k.send(ActorCommand::Stop).await;
|
||||||
drop(k);
|
drop(k);
|
||||||
|
@ -257,8 +252,6 @@ impl PlayerRegistry {
|
||||||
/// The player registry state representation.
|
/// The player registry state representation.
|
||||||
struct PlayerRegistryInner {
|
struct PlayerRegistryInner {
|
||||||
room_registry: RoomRegistry,
|
room_registry: RoomRegistry,
|
||||||
storage: Storage,
|
|
||||||
/// Active player actors.
|
|
||||||
players: HashMap<PlayerId, (PlayerHandle, JoinHandle<Player>)>,
|
players: HashMap<PlayerId, (PlayerHandle, JoinHandle<Player>)>,
|
||||||
metric_active_players: IntGauge,
|
metric_active_players: IntGauge,
|
||||||
}
|
}
|
||||||
|
@ -266,49 +259,32 @@ struct PlayerRegistryInner {
|
||||||
/// Player actor inner state representation.
|
/// Player actor inner state representation.
|
||||||
struct Player {
|
struct Player {
|
||||||
player_id: PlayerId,
|
player_id: PlayerId,
|
||||||
storage_id: u32,
|
|
||||||
connections: AnonTable<Sender<Updates>>,
|
connections: AnonTable<Sender<Updates>>,
|
||||||
my_rooms: HashMap<RoomId, RoomHandle>,
|
my_rooms: HashMap<RoomId, RoomHandle>,
|
||||||
banned_from: HashSet<RoomId>,
|
banned_from: HashSet<RoomId>,
|
||||||
rx: Receiver<ActorCommand>,
|
rx: Receiver<ActorCommand>,
|
||||||
handle: PlayerHandle,
|
handle: PlayerHandle,
|
||||||
rooms: RoomRegistry,
|
rooms: RoomRegistry,
|
||||||
storage: Storage,
|
|
||||||
}
|
}
|
||||||
impl Player {
|
impl Player {
|
||||||
async fn launch(player_id: PlayerId, rooms: RoomRegistry, storage: Storage) -> (PlayerHandle, JoinHandle<Player>) {
|
fn launch(player_id: PlayerId, rooms: RoomRegistry) -> (PlayerHandle, JoinHandle<Player>) {
|
||||||
let (tx, rx) = channel(32);
|
let (tx, rx) = channel(32);
|
||||||
let handle = PlayerHandle { tx };
|
let handle = PlayerHandle { tx };
|
||||||
let handle_clone = handle.clone();
|
let handle_clone = handle.clone();
|
||||||
let storage_id = storage.retrieve_user_id_by_name(player_id.as_inner()).await.unwrap().unwrap();
|
|
||||||
let player = Player {
|
let player = Player {
|
||||||
player_id,
|
player_id,
|
||||||
storage_id,
|
|
||||||
// connections are empty when the actor is just started
|
|
||||||
connections: AnonTable::new(),
|
connections: AnonTable::new(),
|
||||||
// room handlers will be loaded later in the started task
|
|
||||||
my_rooms: HashMap::new(),
|
my_rooms: HashMap::new(),
|
||||||
// TODO implement and load bans
|
banned_from: HashSet::from([RoomId::from("Empty").unwrap()]),
|
||||||
banned_from: HashSet::new(),
|
|
||||||
rx,
|
rx,
|
||||||
handle,
|
handle,
|
||||||
rooms,
|
rooms,
|
||||||
storage,
|
|
||||||
};
|
};
|
||||||
let fiber = tokio::task::spawn(player.main_loop());
|
let fiber = tokio::task::spawn(player.main_loop());
|
||||||
(handle_clone, fiber)
|
(handle_clone, fiber)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn main_loop(mut self) -> Self {
|
async fn main_loop(mut self) -> Self {
|
||||||
let rooms = self.storage.get_rooms_of_a_user(self.storage_id).await.unwrap();
|
|
||||||
for room_id in rooms {
|
|
||||||
let room = self.rooms.get_room(&room_id).await;
|
|
||||||
if let Some(room) = room {
|
|
||||||
self.my_rooms.insert(room_id, room);
|
|
||||||
} else {
|
|
||||||
tracing::error!("Room #{room_id:?} not found");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
while let Some(cmd) = self.rx.recv().await {
|
while let Some(cmd) = self.rx.recv().await {
|
||||||
match cmd {
|
match cmd {
|
||||||
ActorCommand::AddConnection { sender, promise } => {
|
ActorCommand::AddConnection { sender, promise } => {
|
||||||
|
@ -396,8 +372,7 @@ impl Player {
|
||||||
todo!();
|
todo!();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
room.add_member(&self.player_id, self.storage_id).await;
|
room.subscribe(self.player_id.clone(), self.handle.clone()).await;
|
||||||
room.subscribe(&self.player_id, self.handle.clone()).await;
|
|
||||||
self.my_rooms.insert(room_id.clone(), room.clone());
|
self.my_rooms.insert(room_id.clone(), room.clone());
|
||||||
let room_info = room.get_room_info().await;
|
let room_info = room.get_room_info().await;
|
||||||
let update = Updates::RoomJoined {
|
let update = Updates::RoomJoined {
|
||||||
|
@ -412,7 +387,6 @@ impl Player {
|
||||||
let room = self.my_rooms.remove(&room_id);
|
let room = self.my_rooms.remove(&room_id);
|
||||||
if let Some(room) = room {
|
if let Some(room) = room {
|
||||||
room.unsubscribe(&self.player_id).await;
|
room.unsubscribe(&self.player_id).await;
|
||||||
room.remove_member(&self.player_id, self.storage_id).await;
|
|
||||||
}
|
}
|
||||||
let update = Updates::RoomLeft {
|
let update = Updates::RoomLeft {
|
||||||
room_id,
|
room_id,
|
||||||
|
@ -422,11 +396,12 @@ impl Player {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_message(&mut self, connection_id: ConnectionId, room_id: RoomId, body: Str) {
|
async fn send_message(&mut self, connection_id: ConnectionId, room_id: RoomId, body: Str) {
|
||||||
let Some(room) = self.my_rooms.get(&room_id) else {
|
let room = self.rooms.get_room(&room_id).await;
|
||||||
|
if let Some(room) = room {
|
||||||
|
room.send_message(self.player_id.clone(), body.clone()).await;
|
||||||
|
} else {
|
||||||
tracing::info!("no room found");
|
tracing::info!("no room found");
|
||||||
return;
|
}
|
||||||
};
|
|
||||||
room.send_message(&self.player_id, body.clone()).await;
|
|
||||||
let update = Updates::NewMessage {
|
let update = Updates::NewMessage {
|
||||||
room_id,
|
room_id,
|
||||||
author_id: self.player_id.clone(),
|
author_id: self.player_id.clone(),
|
||||||
|
@ -436,11 +411,12 @@ impl Player {
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn change_topic(&mut self, connection_id: ConnectionId, room_id: RoomId, new_topic: Str) {
|
async fn change_topic(&mut self, connection_id: ConnectionId, room_id: RoomId, new_topic: Str) {
|
||||||
let Some(room) = self.my_rooms.get(&room_id) else {
|
let room = self.rooms.get_room(&room_id).await;
|
||||||
|
if let Some(mut room) = room {
|
||||||
|
room.set_topic(self.player_id.clone(), new_topic.clone()).await;
|
||||||
|
} else {
|
||||||
tracing::info!("no room found");
|
tracing::info!("no room found");
|
||||||
return;
|
}
|
||||||
};
|
|
||||||
room.set_topic(&self.player_id, new_topic.clone()).await;
|
|
||||||
let update = Updates::RoomTopicChanged { room_id, new_topic };
|
let update = Updates::RoomTopicChanged { room_id, new_topic };
|
||||||
self.broadcast_update(update, connection_id).await;
|
self.broadcast_update(update, connection_id).await;
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,9 +11,6 @@ use tokio::sync::Mutex;
|
||||||
|
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
|
||||||
mod room;
|
|
||||||
mod user;
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
pub struct StorageConfig {
|
pub struct StorageConfig {
|
||||||
pub db_path: String,
|
pub db_path: String,
|
||||||
|
@ -51,7 +48,7 @@ impl Storage {
|
||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn retrieve_room_by_name(&self, name: &str) -> Result<Option<StoredRoom>> {
|
pub async fn retrieve_room_by_name(&mut self, name: &str) -> Result<Option<StoredRoom>> {
|
||||||
let mut executor = self.conn.lock().await;
|
let mut executor = self.conn.lock().await;
|
||||||
let res = sqlx::query_as(
|
let res = sqlx::query_as(
|
||||||
"select id, name, topic, message_count
|
"select id, name, topic, message_count
|
||||||
|
@ -90,15 +87,14 @@ 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, created_at)
|
"insert into messages(room_id, id, content, author_id)
|
||||||
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?;
|
||||||
|
|
|
@ -1,48 +0,0 @@
|
||||||
use anyhow::Result;
|
|
||||||
|
|
||||||
use crate::repo::Storage;
|
|
||||||
|
|
||||||
impl Storage {
|
|
||||||
pub async fn add_room_member(&self, room_id: u32, player_id: u32) -> Result<()> {
|
|
||||||
let mut executor = self.conn.lock().await;
|
|
||||||
sqlx::query(
|
|
||||||
"insert into memberships(user_id, room_id, status)
|
|
||||||
values (?, ?, 1);",
|
|
||||||
)
|
|
||||||
.bind(player_id)
|
|
||||||
.bind(room_id)
|
|
||||||
.execute(&mut *executor)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn remove_room_member(&self, room_id: u32, player_id: u32) -> Result<()> {
|
|
||||||
let mut executor = self.conn.lock().await;
|
|
||||||
sqlx::query(
|
|
||||||
"delete from memberships
|
|
||||||
where user_id = ? and room_id = ?;",
|
|
||||||
)
|
|
||||||
.bind(player_id)
|
|
||||||
.bind(room_id)
|
|
||||||
.execute(&mut *executor)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn set_room_topic(&mut self, id: u32, topic: &str) -> Result<()> {
|
|
||||||
let mut executor = self.conn.lock().await;
|
|
||||||
sqlx::query(
|
|
||||||
"update rooms
|
|
||||||
set topic = ?
|
|
||||||
where id = ?;",
|
|
||||||
)
|
|
||||||
.bind(topic)
|
|
||||||
.bind(id)
|
|
||||||
.fetch_optional(&mut *executor)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,30 +0,0 @@
|
||||||
use anyhow::Result;
|
|
||||||
|
|
||||||
use crate::repo::Storage;
|
|
||||||
use crate::room::RoomId;
|
|
||||||
|
|
||||||
impl Storage {
|
|
||||||
pub async fn retrieve_user_id_by_name(&self, name: &str) -> Result<Option<u32>> {
|
|
||||||
let mut executor = self.conn.lock().await;
|
|
||||||
let res: Option<(u32,)> = sqlx::query_as("select u.id from users u where u.name = ?;")
|
|
||||||
.bind(name)
|
|
||||||
.fetch_optional(&mut *executor)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(res.map(|(id,)| id))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_rooms_of_a_user(&self, user_id: u32) -> Result<Vec<RoomId>> {
|
|
||||||
let mut executor = self.conn.lock().await;
|
|
||||||
let res: Vec<(String,)> = sqlx::query_as(
|
|
||||||
"select r.name
|
|
||||||
from memberships m inner join rooms r on m.room_id = r.id
|
|
||||||
where m.user_id = ?;",
|
|
||||||
)
|
|
||||||
.bind(user_id)
|
|
||||||
.fetch_all(&mut *executor)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
res.into_iter().map(|(room_id,)| RoomId::from(room_id)).collect()
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,5 +1,4 @@
|
||||||
//! Domain of rooms — chats with multiple participants.
|
//! Domain of rooms — chats with multiple participants.
|
||||||
use std::collections::HashSet;
|
|
||||||
use std::{collections::HashMap, hash::Hash, sync::Arc};
|
use std::{collections::HashMap, hash::Hash, sync::Arc};
|
||||||
|
|
||||||
use prometheus::{IntGauge, Registry as MetricRegistry};
|
use prometheus::{IntGauge, Registry as MetricRegistry};
|
||||||
|
@ -49,9 +48,27 @@ impl RoomRegistry {
|
||||||
|
|
||||||
pub async fn get_or_create_room(&mut self, room_id: RoomId) -> Result<RoomHandle> {
|
pub async fn get_or_create_room(&mut self, room_id: RoomId) -> Result<RoomHandle> {
|
||||||
let mut inner = self.0.write().await;
|
let mut inner = self.0.write().await;
|
||||||
if let Some(room_handle) = inner.get_or_load_room(&room_id).await? {
|
if let Some(room_handle) = inner.rooms.get(&room_id) {
|
||||||
|
// room was already loaded into memory
|
||||||
|
log::debug!("Room {} was loaded already", &room_id.0);
|
||||||
Ok(room_handle.clone())
|
Ok(room_handle.clone())
|
||||||
|
} else if let Some(stored_room) = inner.storage.retrieve_room_by_name(&*room_id.0).await? {
|
||||||
|
// room exists, but was not loaded
|
||||||
|
log::debug!("Loading room {}...", &room_id.0);
|
||||||
|
let room = Room {
|
||||||
|
storage_id: stored_room.id,
|
||||||
|
room_id: room_id.clone(),
|
||||||
|
subscriptions: HashMap::new(), // TODO figure out how to populate subscriptions
|
||||||
|
topic: stored_room.topic.into(),
|
||||||
|
message_count: stored_room.message_count,
|
||||||
|
storage: inner.storage.clone(),
|
||||||
|
};
|
||||||
|
let room_handle = RoomHandle(Arc::new(AsyncRwLock::new(room)));
|
||||||
|
inner.rooms.insert(room_id, room_handle.clone());
|
||||||
|
inner.metric_active_rooms.inc();
|
||||||
|
Ok(room_handle)
|
||||||
} else {
|
} else {
|
||||||
|
// room does not exist, create it and load
|
||||||
log::debug!("Creating room {}...", &room_id.0);
|
log::debug!("Creating room {}...", &room_id.0);
|
||||||
let topic = "New room";
|
let topic = "New room";
|
||||||
let id = inner.storage.create_new_room(&*room_id.0, &*topic).await?;
|
let id = inner.storage.create_new_room(&*room_id.0, &*topic).await?;
|
||||||
|
@ -59,7 +76,6 @@ impl RoomRegistry {
|
||||||
storage_id: id,
|
storage_id: id,
|
||||||
room_id: room_id.clone(),
|
room_id: room_id.clone(),
|
||||||
subscriptions: HashMap::new(),
|
subscriptions: HashMap::new(),
|
||||||
members: HashSet::new(),
|
|
||||||
topic: topic.into(),
|
topic: topic.into(),
|
||||||
message_count: 0,
|
message_count: 0,
|
||||||
storage: inner.storage.clone(),
|
storage: inner.storage.clone(),
|
||||||
|
@ -72,8 +88,9 @@ impl RoomRegistry {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_room(&self, room_id: &RoomId) -> Option<RoomHandle> {
|
pub async fn get_room(&self, room_id: &RoomId) -> Option<RoomHandle> {
|
||||||
let mut inner = self.0.write().await;
|
let inner = self.0.read().await;
|
||||||
inner.get_or_load_room(room_id).await.unwrap()
|
let res = inner.rooms.get(room_id);
|
||||||
|
res.map(|r| r.clone())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_all_rooms(&self) -> Vec<RoomInfo> {
|
pub async fn get_all_rooms(&self) -> Vec<RoomInfo> {
|
||||||
|
@ -96,66 +113,17 @@ struct RoomRegistryInner {
|
||||||
storage: Storage,
|
storage: Storage,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RoomRegistryInner {
|
|
||||||
async fn get_or_load_room(&mut self, room_id: &RoomId) -> Result<Option<RoomHandle>> {
|
|
||||||
if let Some(room_handle) = self.rooms.get(room_id) {
|
|
||||||
log::debug!("Room {} was loaded already", &room_id.0);
|
|
||||||
Ok(Some(room_handle.clone()))
|
|
||||||
} else if let Some(stored_room) = self.storage.retrieve_room_by_name(&*room_id.0).await? {
|
|
||||||
log::debug!("Loading room {}...", &room_id.0);
|
|
||||||
let room = Room {
|
|
||||||
storage_id: stored_room.id,
|
|
||||||
room_id: room_id.clone(),
|
|
||||||
subscriptions: HashMap::new(),
|
|
||||||
members: HashSet::new(), // TODO load members from storage
|
|
||||||
topic: stored_room.topic.into(),
|
|
||||||
message_count: stored_room.message_count,
|
|
||||||
storage: self.storage.clone(),
|
|
||||||
};
|
|
||||||
let room_handle = RoomHandle(Arc::new(AsyncRwLock::new(room)));
|
|
||||||
self.rooms.insert(room_id.clone(), room_handle.clone());
|
|
||||||
self.metric_active_rooms.inc();
|
|
||||||
Ok(Some(room_handle))
|
|
||||||
} else {
|
|
||||||
tracing::debug!("Room {} does not exist", &room_id.0);
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RoomHandle(Arc<AsyncRwLock<Room>>);
|
pub struct RoomHandle(Arc<AsyncRwLock<Room>>);
|
||||||
impl RoomHandle {
|
impl RoomHandle {
|
||||||
pub async fn subscribe(&self, player_id: &PlayerId, player_handle: PlayerHandle) {
|
pub async fn subscribe(&self, player_id: PlayerId, player_handle: PlayerHandle) {
|
||||||
let mut lock = self.0.write().await;
|
let mut lock = self.0.write().await;
|
||||||
tracing::info!("Adding a subscriber to a room");
|
lock.add_subscriber(player_id, player_handle).await;
|
||||||
lock.subscriptions.insert(player_id.clone(), player_handle);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn add_member(&self, player_id: &PlayerId, player_storage_id: u32) {
|
|
||||||
let mut lock = self.0.write().await;
|
|
||||||
tracing::info!("Adding a new member to a room");
|
|
||||||
let room_storage_id = lock.storage_id;
|
|
||||||
lock.storage.add_room_member(room_storage_id, player_storage_id).await.unwrap();
|
|
||||||
lock.members.insert(player_id.clone());
|
|
||||||
let update = Updates::RoomJoined {
|
|
||||||
room_id: lock.room_id.clone(),
|
|
||||||
new_member_id: player_id.clone(),
|
|
||||||
};
|
|
||||||
lock.broadcast_update(update, player_id).await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn unsubscribe(&self, player_id: &PlayerId) {
|
pub async fn unsubscribe(&self, player_id: &PlayerId) {
|
||||||
let mut lock = self.0.write().await;
|
let mut lock = self.0.write().await;
|
||||||
lock.subscriptions.remove(player_id);
|
lock.subscriptions.remove(player_id);
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn remove_member(&self, player_id: &PlayerId, player_storage_id: u32) {
|
|
||||||
let mut lock = self.0.write().await;
|
|
||||||
tracing::info!("Removing a member from a room");
|
|
||||||
let room_storage_id = lock.storage_id;
|
|
||||||
lock.storage.remove_room_member(room_storage_id, player_storage_id).await.unwrap();
|
|
||||||
lock.members.remove(player_id);
|
|
||||||
let update = Updates::RoomLeft {
|
let update = Updates::RoomLeft {
|
||||||
room_id: lock.room_id.clone(),
|
room_id: lock.room_id.clone(),
|
||||||
former_member_id: player_id.clone(),
|
former_member_id: player_id.clone(),
|
||||||
|
@ -163,7 +131,7 @@ impl RoomHandle {
|
||||||
lock.broadcast_update(update, player_id).await;
|
lock.broadcast_update(update, player_id).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_message(&self, player_id: &PlayerId, body: Str) {
|
pub async fn send_message(&self, player_id: PlayerId, body: Str) {
|
||||||
let mut lock = self.0.write().await;
|
let mut lock = self.0.write().await;
|
||||||
let res = lock.send_message(player_id, body).await;
|
let res = lock.send_message(player_id, body).await;
|
||||||
if let Err(err) = res {
|
if let Err(err) = res {
|
||||||
|
@ -180,16 +148,14 @@ impl RoomHandle {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_topic(&self, changer_id: &PlayerId, new_topic: Str) {
|
pub async fn set_topic(&mut self, changer_id: PlayerId, new_topic: Str) {
|
||||||
let mut lock = self.0.write().await;
|
let mut lock = self.0.write().await;
|
||||||
let storage_id = lock.storage_id;
|
|
||||||
lock.topic = new_topic.clone();
|
lock.topic = new_topic.clone();
|
||||||
lock.storage.set_room_topic(storage_id, &new_topic).await.unwrap();
|
|
||||||
let update = Updates::RoomTopicChanged {
|
let update = Updates::RoomTopicChanged {
|
||||||
room_id: lock.room_id.clone(),
|
room_id: lock.room_id.clone(),
|
||||||
new_topic: new_topic.clone(),
|
new_topic: new_topic.clone(),
|
||||||
};
|
};
|
||||||
lock.broadcast_update(update, changer_id).await;
|
lock.broadcast_update(update, &changer_id).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -200,15 +166,23 @@ struct Room {
|
||||||
room_id: RoomId,
|
room_id: RoomId,
|
||||||
/// Player actors on the local node which are subscribed to this room's updates.
|
/// Player actors on the local node which are subscribed to this room's updates.
|
||||||
subscriptions: HashMap<PlayerId, PlayerHandle>,
|
subscriptions: HashMap<PlayerId, PlayerHandle>,
|
||||||
/// Members of the room.
|
|
||||||
members: HashSet<PlayerId>,
|
|
||||||
/// The total number of messages. Used to calculate the id of the new message.
|
/// The total number of messages. Used to calculate the id of the new message.
|
||||||
message_count: u32,
|
message_count: u32,
|
||||||
topic: Str,
|
topic: Str,
|
||||||
storage: Storage,
|
storage: Storage,
|
||||||
}
|
}
|
||||||
impl Room {
|
impl Room {
|
||||||
async fn send_message(&mut self, author_id: &PlayerId, body: Str) -> Result<()> {
|
async fn add_subscriber(&mut self, player_id: PlayerId, player_handle: PlayerHandle) {
|
||||||
|
tracing::info!("Adding a subscriber to room");
|
||||||
|
self.subscriptions.insert(player_id.clone(), player_handle);
|
||||||
|
let update = Updates::RoomJoined {
|
||||||
|
room_id: self.room_id.clone(),
|
||||||
|
new_member_id: player_id.clone(),
|
||||||
|
};
|
||||||
|
self.broadcast_update(update, &player_id).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_message(&mut self, author_id: PlayerId, body: Str) -> Result<()> {
|
||||||
tracing::info!("Adding a message to room");
|
tracing::info!("Adding a message to room");
|
||||||
self.storage.insert_message(self.storage_id, self.message_count, &body, &*author_id.as_inner()).await?;
|
self.storage.insert_message(self.storage_id, self.message_count, &body, &*author_id.as_inner()).await?;
|
||||||
self.message_count += 1;
|
self.message_count += 1;
|
||||||
|
@ -217,7 +191,7 @@ impl Room {
|
||||||
author_id: author_id.clone(),
|
author_id: author_id.clone(),
|
||||||
body,
|
body,
|
||||||
};
|
};
|
||||||
self.broadcast_update(update, author_id).await;
|
self.broadcast_update(update, &author_id).await;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -86,249 +86,6 @@ async fn handle_socket(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
struct RegistrationState {
|
|
||||||
/// The last received `NICK` message.
|
|
||||||
future_nickname: Option<Str>,
|
|
||||||
/// The last received `USER` message.
|
|
||||||
future_username: Option<(Str, Str)>,
|
|
||||||
enabled_capabilities: Capabilities,
|
|
||||||
/// `CAP LS` or `CAP REQ` was received, but not `CAP END`.
|
|
||||||
cap_negotiation_in_progress: bool,
|
|
||||||
/// The last received `PASS` message.
|
|
||||||
pass: Option<Str>,
|
|
||||||
authentication_started: bool,
|
|
||||||
validated_user: Option<Str>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RegistrationState {
|
|
||||||
fn new() -> RegistrationState {
|
|
||||||
RegistrationState {
|
|
||||||
future_nickname: None,
|
|
||||||
future_username: None,
|
|
||||||
enabled_capabilities: Capabilities::None,
|
|
||||||
cap_negotiation_in_progress: false,
|
|
||||||
pass: None,
|
|
||||||
authentication_started: false,
|
|
||||||
validated_user: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Handle an incoming message from the client during the registration process.
|
|
||||||
///
|
|
||||||
/// Returns `Some` if the user is fully registered, `None` if the registration is still in progress.
|
|
||||||
async fn handle_msg(
|
|
||||||
&mut self,
|
|
||||||
msg: ClientMessage,
|
|
||||||
writer: &mut BufWriter<WriteHalf<'_>>,
|
|
||||||
storage: &mut Storage,
|
|
||||||
config: &ServerConfig,
|
|
||||||
) -> Result<Option<RegisteredUser>> {
|
|
||||||
match msg {
|
|
||||||
ClientMessage::Pass { password } => {
|
|
||||||
self.pass = Some(password);
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
ClientMessage::Capability { subcommand } => match subcommand {
|
|
||||||
CapabilitySubcommand::List { code: _ } => {
|
|
||||||
self.cap_negotiation_in_progress = true;
|
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::Cap {
|
|
||||||
target: self.future_nickname.clone().unwrap_or_else(|| "*".into()),
|
|
||||||
subcmd: CapSubBody::Ls("sasl=PLAIN".into()),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
CapabilitySubcommand::Req(caps) => {
|
|
||||||
self.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 {
|
|
||||||
self.enabled_capabilities &= !Capabilities::Sasl;
|
|
||||||
} else {
|
|
||||||
self.enabled_capabilities |= Capabilities::Sasl;
|
|
||||||
}
|
|
||||||
acked.push(cap);
|
|
||||||
} else {
|
|
||||||
naked.push(cap);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut ack_body = String::new();
|
|
||||||
for cap in acked {
|
|
||||||
if cap.to_disable {
|
|
||||||
ack_body.push('-');
|
|
||||||
}
|
|
||||||
ack_body += &*cap.name;
|
|
||||||
}
|
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::Cap {
|
|
||||||
target: self.future_nickname.clone().unwrap_or_else(|| "*".into()),
|
|
||||||
subcmd: CapSubBody::Ack(ack_body.into()),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
CapabilitySubcommand::End => {
|
|
||||||
let Some((ref username, ref realname)) = self.future_username else {
|
|
||||||
self.cap_negotiation_in_progress = false;
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
let Some(nickname) = self.future_nickname.clone() else {
|
|
||||||
self.cap_negotiation_in_progress = false;
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
let username = username.clone();
|
|
||||||
let realname = realname.clone();
|
|
||||||
let candidate_user = RegisteredUser {
|
|
||||||
nickname: nickname.clone(),
|
|
||||||
username,
|
|
||||||
realname,
|
|
||||||
};
|
|
||||||
self.finalize_auth(candidate_user, writer, storage, config).await
|
|
||||||
}
|
|
||||||
},
|
|
||||||
ClientMessage::Nick { nickname } => {
|
|
||||||
if self.cap_negotiation_in_progress {
|
|
||||||
self.future_nickname = Some(nickname);
|
|
||||||
Ok(None)
|
|
||||||
} else if let Some((username, realname)) = &self.future_username.clone() {
|
|
||||||
let candidate_user = RegisteredUser {
|
|
||||||
nickname: nickname.clone(),
|
|
||||||
username: username.clone(),
|
|
||||||
realname: realname.clone(),
|
|
||||||
};
|
|
||||||
self.finalize_auth(candidate_user, writer, storage, config).await
|
|
||||||
} else {
|
|
||||||
self.future_nickname = Some(nickname);
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ClientMessage::User { username, realname } => {
|
|
||||||
if self.cap_negotiation_in_progress {
|
|
||||||
self.future_username = Some((username, realname));
|
|
||||||
Ok(None)
|
|
||||||
} else if let Some(nickname) = self.future_nickname.clone() {
|
|
||||||
let candidate_user = RegisteredUser {
|
|
||||||
nickname: nickname.clone(),
|
|
||||||
username,
|
|
||||||
realname,
|
|
||||||
};
|
|
||||||
self.finalize_auth(candidate_user, writer, storage, config).await
|
|
||||||
} else {
|
|
||||||
self.future_username = Some((username, realname));
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ClientMessage::Authenticate(body) => {
|
|
||||||
if !self.authentication_started {
|
|
||||||
tracing::debug!("Received authentication request");
|
|
||||||
if &*body == "PLAIN" {
|
|
||||||
tracing::debug!("Authentication request with method PLAIN");
|
|
||||||
self.authentication_started = true;
|
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::Authenticate("+".into()),
|
|
||||||
}
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
Ok(None)
|
|
||||||
} else {
|
|
||||||
let target = self.future_nickname.clone().unwrap_or_else(|| "*".into());
|
|
||||||
sasl_fail_message(config.server_name.clone(), target, "Unsupported mechanism".into())
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
let body = AuthBody::from_str(body.as_bytes())?;
|
|
||||||
if let Err(e) = auth_user(storage, &body.login, &body.password).await {
|
|
||||||
tracing::warn!("Authentication failed: {:?}", e);
|
|
||||||
let target = self.future_nickname.clone().unwrap_or_else(|| "*".into());
|
|
||||||
sasl_fail_message(config.server_name.clone(), target, "Bad credentials".into())
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
Ok(None)
|
|
||||||
} else {
|
|
||||||
let login: Str = body.login.into();
|
|
||||||
self.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?;
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO handle abortion of authentication
|
|
||||||
}
|
|
||||||
_ => Ok(None),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn finalize_auth(
|
|
||||||
&mut self,
|
|
||||||
candidate_user: RegisteredUser,
|
|
||||||
writer: &mut BufWriter<WriteHalf<'_>>,
|
|
||||||
storage: &mut Storage,
|
|
||||||
config: &ServerConfig,
|
|
||||||
) -> Result<Option<RegisteredUser>> {
|
|
||||||
if self.enabled_capabilities.contains(Capabilities::Sasl)
|
|
||||||
&& self.validated_user.as_ref() == Some(&candidate_user.nickname)
|
|
||||||
{
|
|
||||||
Ok(Some(candidate_user))
|
|
||||||
} else {
|
|
||||||
let Some(candidate_password) = &self.pass else {
|
|
||||||
sasl_fail_message(
|
|
||||||
config.server_name.clone(),
|
|
||||||
candidate_user.nickname.clone(),
|
|
||||||
"User credentials was not provided".into(),
|
|
||||||
)
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
return Ok(None);
|
|
||||||
};
|
|
||||||
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
|
||||||
Ok(Some(candidate_user))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_registration<'a>(
|
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>>,
|
||||||
|
@ -337,7 +94,14 @@ async fn handle_registration<'a>(
|
||||||
) -> Result<RegisteredUser> {
|
) -> Result<RegisteredUser> {
|
||||||
let mut buffer = vec![];
|
let mut buffer = vec![];
|
||||||
|
|
||||||
let mut state = RegistrationState::new();
|
let mut future_nickname: Option<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 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;
|
||||||
|
@ -368,8 +132,218 @@ async fn handle_registration<'a>(
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
tracing::debug!("Incoming IRC message: {msg:?}");
|
tracing::debug!("Incoming IRC message: {msg:?}");
|
||||||
if let Some(user) = state.handle_msg(msg, writer, storage, config).await? {
|
match msg {
|
||||||
break Ok(user);
|
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()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
}
|
||||||
|
CapabilitySubcommand::Req(caps) => {
|
||||||
|
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 {
|
||||||
|
naked.push(cap);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut ack_body = String::new();
|
||||||
|
for cap in acked {
|
||||||
|
if cap.to_disable {
|
||||||
|
ack_body.push('-');
|
||||||
|
}
|
||||||
|
ack_body += &*cap.name;
|
||||||
|
}
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::Cap {
|
||||||
|
target: future_nickname.clone().unwrap_or_else(|| "*".into()),
|
||||||
|
subcmd: CapSubBody::Ack(ack_body.into()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
}
|
||||||
|
CapabilitySubcommand::End => {
|
||||||
|
let Some((ref username, ref realname)) = future_username else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
let Some(nickname) = future_nickname.clone() else {
|
||||||
|
todo!();
|
||||||
|
};
|
||||||
|
let username = username.clone();
|
||||||
|
let realname = realname.clone();
|
||||||
|
let candidate_user = RegisteredUser {
|
||||||
|
nickname: nickname.clone(),
|
||||||
|
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 {
|
||||||
|
sasl_fail_message(
|
||||||
|
config.server_name.clone(),
|
||||||
|
nickname.clone(),
|
||||||
|
"User credentials was not provided".into(),
|
||||||
|
)
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
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: nickname.clone(),
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
};
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
sasl_fail_message(
|
||||||
|
config.server_name.clone(),
|
||||||
|
nickname.clone(),
|
||||||
|
"User credentials was not provided".into(),
|
||||||
|
)
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
|
break Ok(candidate_user);
|
||||||
|
} else {
|
||||||
|
future_nickname = Some(nickname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ClientMessage::User { username, realname } => {
|
||||||
|
if cap_negotiation_in_progress {
|
||||||
|
future_username = Some((username, realname));
|
||||||
|
} else if let Some(nickname) = future_nickname.clone() {
|
||||||
|
let candidate_user = RegisteredUser {
|
||||||
|
nickname: nickname.clone(),
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
};
|
||||||
|
let Some(candidate_password) = pass else {
|
||||||
|
sasl_fail_message(
|
||||||
|
config.server_name.clone(),
|
||||||
|
nickname.clone(),
|
||||||
|
"User credentials was not provided".into(),
|
||||||
|
)
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
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 {
|
||||||
|
if let Some(nickname) = future_nickname.clone() {
|
||||||
|
sasl_fail_message(
|
||||||
|
config.server_name.clone(),
|
||||||
|
nickname.clone(),
|
||||||
|
"Unsupported mechanism".into(),
|
||||||
|
)
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
} else {
|
||||||
|
break Err(anyhow::Error::msg("Wrong authentication sequence"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let body = AuthBody::from_str(body.as_bytes())?;
|
||||||
|
if let Err(e) = auth_user(storage, &body.login, &body.password).await {
|
||||||
|
tracing::warn!("Authentication failed: {:?}", e);
|
||||||
|
if let Some(nickname) = future_nickname.clone() {
|
||||||
|
sasl_fail_message(config.server_name.clone(), nickname.clone(), "Bad credentials".into())
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
} else {
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
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();
|
||||||
}?;
|
}?;
|
||||||
|
@ -418,7 +392,7 @@ async fn handle_registered_socket<'a>(
|
||||||
log::info!("Handling registered user: {user:?}");
|
log::info!("Handling registered user: {user:?}");
|
||||||
|
|
||||||
let player_id = PlayerId::from(user.nickname.clone())?;
|
let player_id = PlayerId::from(user.nickname.clone())?;
|
||||||
let mut connection = players.connect_to_player(&player_id).await;
|
let mut connection = players.connect_to_player(player_id.clone()).await;
|
||||||
let text: Str = format!("Welcome to {} Server", &config.server_name).into();
|
let text: Str = format!("Welcome to {} Server", &config.server_name).into();
|
||||||
|
|
||||||
ServerMessage {
|
ServerMessage {
|
||||||
|
|
|
@ -111,36 +111,7 @@ impl TestServer {
|
||||||
})
|
})
|
||||||
.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(), storage.clone(), &mut metrics).unwrap();
|
let players = PlayerRegistry::empty(rooms.clone(), &mut metrics).unwrap();
|
||||||
let server = launch(config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
|
||||||
Ok(TestServer {
|
|
||||||
metrics,
|
|
||||||
storage,
|
|
||||||
rooms,
|
|
||||||
players,
|
|
||||||
server,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn reboot(mut self) -> Result<TestServer> {
|
|
||||||
let config = ServerConfig {
|
|
||||||
listen_on: "127.0.0.1:0".parse().unwrap(),
|
|
||||||
server_name: "testserver".into(),
|
|
||||||
};
|
|
||||||
let TestServer {
|
|
||||||
mut metrics,
|
|
||||||
mut storage,
|
|
||||||
rooms,
|
|
||||||
mut players,
|
|
||||||
server,
|
|
||||||
} = self;
|
|
||||||
server.terminate().await?;
|
|
||||||
players.shutdown_all().await.unwrap();
|
|
||||||
drop(players);
|
|
||||||
drop(rooms);
|
|
||||||
let mut metrics = MetricsRegistry::new();
|
|
||||||
let rooms = RoomRegistry::new(&mut metrics, storage.clone()).unwrap();
|
|
||||||
let players = PlayerRegistry::empty(rooms.clone(), storage.clone(), &mut metrics).unwrap();
|
|
||||||
let server = launch(config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
let server = launch(config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
||||||
Ok(TestServer {
|
Ok(TestServer {
|
||||||
metrics,
|
metrics,
|
||||||
|
@ -181,76 +152,6 @@ async fn scenario_basic() -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_join_and_reboot() -> 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);
|
|
||||||
|
|
||||||
// Open a connection and join a channel
|
|
||||||
|
|
||||||
s.send("PASS password").await?;
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.expect_server_introduction("tester").await?;
|
|
||||||
s.expect_nothing().await?;
|
|
||||||
s.send("JOIN #test").await?;
|
|
||||||
s.expect(":tester JOIN #test").await?;
|
|
||||||
s.expect(":testserver 332 tester #test :New room").await?;
|
|
||||||
s.expect(":testserver 353 tester = #test :tester").await?;
|
|
||||||
s.expect(":testserver 366 tester #test :End of /NAMES list").await?;
|
|
||||||
s.send("PRIVMSG #test :Hello").await?;
|
|
||||||
s.send("QUIT :Leaving").await?;
|
|
||||||
s.expect(":testserver ERROR :Leaving the server").await?;
|
|
||||||
s.expect_eof().await?;
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// Open a new connection and expect to be force-joined to the channel
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
|
|
||||||
async fn test(s: &mut TestScope<'_>) -> Result<()> {
|
|
||||||
s.send("PASS password").await?;
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.expect_server_introduction("tester").await?;
|
|
||||||
s.expect(":tester JOIN #test").await?;
|
|
||||||
s.expect(":testserver 332 tester #test :New room").await?;
|
|
||||||
s.expect(":testserver 353 tester = #test :tester").await?;
|
|
||||||
s.expect(":testserver 366 tester #test :End of /NAMES list").await?;
|
|
||||||
s.send("QUIT :Leaving").await?;
|
|
||||||
s.expect(":testserver ERROR :Leaving the server").await?;
|
|
||||||
s.expect_eof().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
test(&mut s).await?;
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// Reboot the server
|
|
||||||
|
|
||||||
let server = server.reboot().await?;
|
|
||||||
|
|
||||||
// Open a new connection and expect to be force-joined to the channel
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
|
|
||||||
test(&mut s).await?;
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// wrap up
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn scenario_force_join_msg() -> Result<()> {
|
async fn scenario_force_join_msg() -> Result<()> {
|
||||||
let mut server = TestServer::start().await?;
|
let mut server = TestServer::start().await?;
|
||||||
|
@ -421,45 +322,6 @@ async fn scenario_cap_full_negotiation() -> Result<()> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_cap_full_negotiation_nick_last() -> 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.expect(":testserver CAP * LS :sasl=PLAIN").await?;
|
|
||||||
s.send("CAP REQ :sasl").await?;
|
|
||||||
s.expect(":testserver CAP * 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.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
|
|
||||||
s.expect_server_introduction("tester").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]
|
#[tokio::test]
|
||||||
async fn scenario_cap_short_negotiation() -> Result<()> {
|
async fn scenario_cap_short_negotiation() -> Result<()> {
|
||||||
let mut server = TestServer::start().await?;
|
let mut server = TestServer::start().await?;
|
||||||
|
@ -545,6 +407,7 @@ async fn scenario_cap_sasl_fail() -> Result<()> {
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn terminate_socket_scenario() -> Result<()> {
|
async fn terminate_socket_scenario() -> Result<()> {
|
||||||
let mut server = TestServer::start().await?;
|
let mut server = TestServer::start().await?;
|
||||||
|
let address: SocketAddr = ("127.0.0.1:0".parse().unwrap());
|
||||||
|
|
||||||
// test scenario
|
// test scenario
|
||||||
|
|
||||||
|
|
|
@ -2,8 +2,8 @@
|
||||||
|
|
||||||
use quick_xml::events::Event;
|
use quick_xml::events::Event;
|
||||||
|
|
||||||
use lavina_core::room::{RoomId, RoomRegistry};
|
use lavina_core::room::RoomRegistry;
|
||||||
use proto_xmpp::bind::{BindResponse, Jid, Name, Server};
|
use proto_xmpp::bind::{BindResponse, Jid, Name, Resource, Server};
|
||||||
use proto_xmpp::client::{Iq, IqError, IqErrorType, IqType};
|
use proto_xmpp::client::{Iq, IqError, IqErrorType, IqType};
|
||||||
use proto_xmpp::disco::{Feature, Identity, InfoQuery, Item, ItemQuery};
|
use proto_xmpp::disco::{Feature, Identity, InfoQuery, Item, ItemQuery};
|
||||||
use proto_xmpp::roster::RosterQuery;
|
use proto_xmpp::roster::RosterQuery;
|
||||||
|
@ -17,16 +17,16 @@ use proto_xmpp::xml::ToXml;
|
||||||
impl<'a> XmppConnection<'a> {
|
impl<'a> XmppConnection<'a> {
|
||||||
pub async fn handle_iq(&self, output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>) {
|
pub async fn handle_iq(&self, output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>) {
|
||||||
match iq.body {
|
match iq.body {
|
||||||
IqClientBody::Bind(_) => {
|
IqClientBody::Bind(b) => {
|
||||||
let req = Iq {
|
let req = Iq {
|
||||||
from: None,
|
from: None,
|
||||||
id: iq.id,
|
id: iq.id,
|
||||||
to: None,
|
to: None,
|
||||||
r#type: IqType::Result,
|
r#type: IqType::Result,
|
||||||
body: BindResponse(Jid {
|
body: BindResponse(Jid {
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
name: Some(Name("darova".into())),
|
||||||
server: Server(self.hostname.clone()),
|
server: Server("localhost".into()),
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
resource: Some(Resource("kek".into())),
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
req.serialize(output);
|
req.serialize(output);
|
||||||
|
@ -52,9 +52,7 @@ impl<'a> XmppConnection<'a> {
|
||||||
req.serialize(output);
|
req.serialize(output);
|
||||||
}
|
}
|
||||||
IqClientBody::DiscoInfo(info) => {
|
IqClientBody::DiscoInfo(info) => {
|
||||||
let response = self.disco_info(iq.to.as_ref(), &info).await;
|
let response = disco_info(iq.to.as_deref(), &info);
|
||||||
match response {
|
|
||||||
Ok(response) => {
|
|
||||||
let req = Iq {
|
let req = Iq {
|
||||||
from: iq.to,
|
from: iq.to,
|
||||||
id: iq.id,
|
id: iq.id,
|
||||||
|
@ -64,20 +62,8 @@ impl<'a> XmppConnection<'a> {
|
||||||
};
|
};
|
||||||
req.serialize(output);
|
req.serialize(output);
|
||||||
}
|
}
|
||||||
Err(response) => {
|
|
||||||
let req = Iq {
|
|
||||||
from: iq.to,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Error,
|
|
||||||
body: response,
|
|
||||||
};
|
|
||||||
req.serialize(output);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
IqClientBody::DiscoItem(item) => {
|
IqClientBody::DiscoItem(item) => {
|
||||||
let response = self.disco_items(iq.to.as_ref(), &item, self.rooms).await;
|
let response = 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,
|
||||||
|
@ -101,17 +87,13 @@ impl<'a> XmppConnection<'a> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn disco_info(&self, to: Option<&Jid>, req: &InfoQuery) -> Result<InfoQuery, IqError> {
|
fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery {
|
||||||
let identity;
|
let identity;
|
||||||
let feature;
|
let feature;
|
||||||
|
|
||||||
match to {
|
match to {
|
||||||
Some(Jid {
|
Some("localhost") => {
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname => {
|
|
||||||
identity = vec![Identity {
|
identity = vec![Identity {
|
||||||
category: "server".into(),
|
category: "server".into(),
|
||||||
name: None,
|
name: None,
|
||||||
|
@ -124,11 +106,7 @@ impl<'a> XmppConnection<'a> {
|
||||||
Feature::new("presence"),
|
Feature::new("presence"),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
Some(Jid {
|
Some("rooms.localhost") => {
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == 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()),
|
||||||
|
@ -140,75 +118,39 @@ impl<'a> XmppConnection<'a> {
|
||||||
Feature::new("http://jabber.org/protocol/muc"),
|
Feature::new("http://jabber.org/protocol/muc"),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
Some(Jid {
|
|
||||||
name: Some(room_name),
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname_rooms => {
|
|
||||||
let room_id = RoomId::from(room_name.0.clone()).unwrap();
|
|
||||||
let Some(_) = self.rooms.get_room(&room_id).await else {
|
|
||||||
// TODO should return item-not-found
|
|
||||||
// example:
|
|
||||||
// <error type="cancel">
|
|
||||||
// <item-not-found xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
|
|
||||||
// <text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" xml:lang="en">Conference room does not exist</text>
|
|
||||||
// </error>
|
|
||||||
return Err(IqError {
|
|
||||||
r#type: IqErrorType::Cancel,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
identity = vec![Identity {
|
|
||||||
category: "conference".into(),
|
|
||||||
name: Some(room_id.into_inner().to_string()),
|
|
||||||
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![];
|
identity = vec![];
|
||||||
feature = vec![];
|
feature = vec![];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
Ok(InfoQuery {
|
InfoQuery {
|
||||||
node: None,
|
node: None,
|
||||||
identity,
|
identity,
|
||||||
feature,
|
feature,
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn disco_items(&self, to: Option<&Jid>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
|
async fn disco_items(to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
|
||||||
let item = match to {
|
let item = match to {
|
||||||
Some(Jid {
|
Some("localhost") => {
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname => {
|
|
||||||
vec![Item {
|
vec![Item {
|
||||||
jid: Jid {
|
jid: Jid {
|
||||||
name: None,
|
name: None,
|
||||||
server: Server(self.hostname_rooms.clone()),
|
server: Server("rooms.localhost".into()),
|
||||||
resource: None,
|
resource: None,
|
||||||
},
|
},
|
||||||
name: None,
|
name: None,
|
||||||
node: None,
|
node: None,
|
||||||
}]
|
}]
|
||||||
}
|
}
|
||||||
Some(Jid {
|
Some("rooms.localhost") => {
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == 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(self.hostname_rooms.clone()),
|
server: Server("rooms.localhost".into()),
|
||||||
resource: None,
|
resource: None,
|
||||||
},
|
},
|
||||||
name: None,
|
name: None,
|
||||||
|
@ -220,4 +162,3 @@ impl<'a> XmppConnection<'a> {
|
||||||
};
|
};
|
||||||
ItemQuery { item }
|
ItemQuery { item }
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
|
@ -9,6 +9,7 @@ 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};
|
||||||
|
@ -43,7 +44,6 @@ 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,17 +52,9 @@ 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -125,12 +117,11 @@ 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, hostname, termination).await {
|
match handle_socket(loaded_config, stream, &socket_addr, players, rooms, storage, 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}"),
|
||||||
}
|
}
|
||||||
|
@ -165,13 +156,12 @@ pub async fn launch(
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_socket(
|
async fn handle_socket(
|
||||||
cert_config: Arc<LoadedConfig>,
|
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}");
|
||||||
|
@ -180,12 +170,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, &hostname).await?;
|
socket_force_tls(&mut buf_reader, &mut buf_writer, &mut reader_buf).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![cert_config.cert.clone()], cert_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...");
|
log::debug!("Accepting TLS connection...");
|
||||||
|
@ -204,10 +194,10 @@ 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, &hostname) => {
|
authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf, &mut storage) => {
|
||||||
match authenticated {
|
match authenticated {
|
||||||
Ok(authenticated) => {
|
Ok(authenticated) => {
|
||||||
let mut connection = players.connect_to_player(&authenticated.player_id).await;
|
let mut connection = players.connect_to_player(authenticated.player_id.clone()).await;
|
||||||
socket_final(
|
socket_final(
|
||||||
&mut xml_reader,
|
&mut xml_reader,
|
||||||
&mut xml_writer,
|
&mut xml_writer,
|
||||||
|
@ -215,7 +205,6 @@ async fn handle_socket(
|
||||||
&authenticated,
|
&authenticated,
|
||||||
&mut connection,
|
&mut connection,
|
||||||
&rooms,
|
&rooms,
|
||||||
&hostname,
|
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
},
|
},
|
||||||
|
@ -236,18 +225,16 @@ 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: hostname.to_string(),
|
from: "localhost".into(),
|
||||||
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(),
|
||||||
|
@ -272,14 +259,12 @@ 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: hostname.to_string(),
|
from: "localhost".into(),
|
||||||
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(),
|
||||||
|
@ -322,13 +307,11 @@ 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.clone())?,
|
player_id: PlayerId::from(name.as_str())?,
|
||||||
xmpp_name: Name(name.clone()),
|
xmpp_name: Name(name.to_string().into()),
|
||||||
xmpp_resource: Resource(name.clone()),
|
xmpp_resource: Resource(name.to_string().into()),
|
||||||
xmpp_muc_name: Resource(name.clone()),
|
xmpp_muc_name: Resource(name.to_string().into()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Err(e) => return Err(e),
|
Err(e) => return Err(e),
|
||||||
|
@ -342,14 +325,12 @@ 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: hostname.to_string(),
|
from: "localhost".into(),
|
||||||
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(),
|
||||||
|
@ -375,15 +356,13 @@ 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 == b'\n' || *x == b' ') {
|
if e.iter().all(|x| *x == 0xA) {
|
||||||
break 's true;
|
break 's true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -433,8 +412,6 @@ 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> {
|
||||||
|
|
|
@ -18,17 +18,17 @@ impl<'a> XmppConnection<'a> {
|
||||||
resource: _,
|
resource: _,
|
||||||
}) = m.to
|
}) = m.to
|
||||||
{
|
{
|
||||||
if server.0.as_ref() == &*self.hostname_rooms && m.r#type == MessageType::Groupchat {
|
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?;
|
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(self.hostname.clone()),
|
server: Server("localhost".into()),
|
||||||
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(self.hostname_rooms.clone()),
|
server: Server("rooms.localhost".into()),
|
||||||
resource: Some(self.user.xmpp_muc_name.clone()),
|
resource: Some(self.user.xmpp_muc_name.clone()),
|
||||||
}),
|
}),
|
||||||
id: m.id,
|
id: m.id,
|
||||||
|
|
|
@ -4,7 +4,7 @@ use quick_xml::events::Event;
|
||||||
|
|
||||||
use lavina_core::prelude::*;
|
use lavina_core::prelude::*;
|
||||||
use lavina_core::room::RoomId;
|
use lavina_core::room::RoomId;
|
||||||
use proto_xmpp::bind::{Jid, Name, Server};
|
use proto_xmpp::bind::{Jid, Server};
|
||||||
use proto_xmpp::client::Presence;
|
use proto_xmpp::client::Presence;
|
||||||
use proto_xmpp::xml::{Ignore, ToXml};
|
use proto_xmpp::xml::{Ignore, ToXml};
|
||||||
|
|
||||||
|
@ -12,59 +12,42 @@ use crate::XmppConnection;
|
||||||
|
|
||||||
impl<'a> XmppConnection<'a> {
|
impl<'a> XmppConnection<'a> {
|
||||||
pub async fn handle_presence(&mut self, output: &mut Vec<Event<'static>>, p: Presence<Ignore>) -> Result<()> {
|
pub async fn handle_presence(&mut self, output: &mut Vec<Event<'static>>, p: Presence<Ignore>) -> Result<()> {
|
||||||
match p.to {
|
let response = if p.to.is_none() {
|
||||||
None => {
|
Presence::<()> {
|
||||||
self.self_presence(output).await;
|
|
||||||
}
|
|
||||||
Some(Jid {
|
|
||||||
name: Some(name),
|
|
||||||
server,
|
|
||||||
// resources in MUCs are members' personas – not implemented (yet?)
|
|
||||||
resource: Some(_),
|
|
||||||
}) if server.0 == self.hostname_rooms => {
|
|
||||||
self.muc_presence(name, output).await?;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
// TODO other presence cases
|
|
||||||
let response = Presence::<()>::default();
|
|
||||||
response.serialize(output);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn self_presence(&mut self, output: &mut Vec<Event<'static>>) {
|
|
||||||
let response = Presence::<()> {
|
|
||||||
to: Some(Jid {
|
to: Some(Jid {
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
name: Some(self.user.xmpp_name.clone()),
|
||||||
server: Server(self.hostname.clone()),
|
server: Server("localhost".into()),
|
||||||
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(self.hostname.clone()),
|
server: Server("localhost".into()),
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
resource: Some(self.user.xmpp_resource.clone()),
|
||||||
}),
|
}),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
|
||||||
response.serialize(output);
|
|
||||||
}
|
}
|
||||||
|
} else if let Some(Jid {
|
||||||
async fn muc_presence(&mut self, name: Name, output: &mut Vec<Event<'static>>) -> Result<()> {
|
name: Some(name),
|
||||||
|
server,
|
||||||
|
resource: Some(resource),
|
||||||
|
}) = p.to
|
||||||
|
{
|
||||||
let a = self.user_handle.join_room(RoomId::from(name.0.clone())?).await?;
|
let a = self.user_handle.join_room(RoomId::from(name.0.clone())?).await?;
|
||||||
// TODO handle bans
|
Presence::<()> {
|
||||||
let response = Presence::<()> {
|
|
||||||
to: Some(Jid {
|
to: Some(Jid {
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
name: Some(self.user.xmpp_name.clone()),
|
||||||
server: Server(self.hostname.clone()),
|
server: Server("localhost".into()),
|
||||||
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(self.hostname_rooms.clone()),
|
server: Server("rooms.localhost".into()),
|
||||||
resource: Some(self.user.xmpp_muc_name.clone()),
|
resource: Some(self.user.xmpp_muc_name.clone()),
|
||||||
}),
|
}),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Presence::<()>::default()
|
||||||
};
|
};
|
||||||
response.serialize(output);
|
response.serialize(output);
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
@ -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(self.hostname.clone()),
|
server: Server("localhost".into()),
|
||||||
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(self.hostname_rooms.clone()),
|
server: Server("rooms.localhost".into()),
|
||||||
resource: Some(Resource(author_id.into_inner().into())),
|
resource: Some(Resource(author_id.into_inner().into())),
|
||||||
}),
|
}),
|
||||||
id: None,
|
id: None,
|
||||||
|
|
|
@ -1,4 +1,5 @@
|
||||||
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;
|
||||||
|
|
||||||
|
@ -19,7 +20,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, RunningServer, ServerConfig};
|
use projection_xmpp::{launch, 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> {
|
||||||
|
@ -121,21 +122,13 @@ impl ServerCertVerifier for IgnoreCertVerification {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct TestServer {
|
#[tokio::test]
|
||||||
metrics: MetricsRegistry,
|
async fn scenario_basic() -> Result<()> {
|
||||||
storage: Storage,
|
tracing_subscriber::fmt::try_init();
|
||||||
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(),
|
||||||
key: "tests/certs/xmpp.key".parse().unwrap(),
|
key: "tests/certs/xmpp.key".parse().unwrap(),
|
||||||
hostname: "localhost".into(),
|
|
||||||
};
|
};
|
||||||
let mut metrics = MetricsRegistry::new();
|
let mut metrics = MetricsRegistry::new();
|
||||||
let mut storage = Storage::open(StorageConfig {
|
let mut storage = Storage::open(StorageConfig {
|
||||||
|
@ -143,28 +136,15 @@ impl TestServer {
|
||||||
})
|
})
|
||||||
.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(), storage.clone(), &mut metrics).unwrap();
|
let players = PlayerRegistry::empty(rooms.clone(), &mut metrics).unwrap();
|
||||||
let server = launch(config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
let server = launch(config, players, rooms, metrics, 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
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
storage.create_user("tester").await?;
|
||||||
server.storage.set_password("tester", "password").await?;
|
storage.set_password("tester", "password").await?;
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
let mut stream = TcpStream::connect(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");
|
||||||
|
|
||||||
|
@ -189,7 +169,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.server.addr.ip()), stream).await?;
|
let mut stream = connector.connect(ServerName::IpAddress(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);
|
||||||
|
@ -203,20 +183,33 @@ async fn scenario_basic() -> Result<()> {
|
||||||
|
|
||||||
// wrap up
|
// wrap up
|
||||||
|
|
||||||
server.server.terminate().await?;
|
server.terminate().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn scenario_basic_without_headers() -> Result<()> {
|
async fn scenario_basic_without_headers() -> Result<()> {
|
||||||
let mut server = TestServer::start().await?;
|
tracing_subscriber::fmt::try_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
|
// test scenario
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
storage.create_user("tester").await?;
|
||||||
server.storage.set_password("tester", "password").await?;
|
storage.set_password("tester", "password").await?;
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
let mut stream = TcpStream::connect(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");
|
||||||
|
|
||||||
|
@ -240,7 +233,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.server.addr.ip()), stream).await?;
|
let mut stream = connector.connect(ServerName::IpAddress(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);
|
||||||
|
@ -253,20 +246,33 @@ async fn scenario_basic_without_headers() -> Result<()> {
|
||||||
|
|
||||||
// wrap up
|
// wrap up
|
||||||
|
|
||||||
server.server.terminate().await?;
|
server.terminate().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn terminate_socket() -> Result<()> {
|
async fn terminate_socket() -> Result<()> {
|
||||||
let mut server = TestServer::start().await?;
|
tracing_subscriber::fmt::try_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();
|
||||||
|
let address: SocketAddr = ("127.0.0.1:0".parse().unwrap());
|
||||||
// test scenario
|
// test scenario
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
storage.create_user("tester").await?;
|
||||||
server.storage.set_password("tester", "password").await?;
|
storage.set_password("tester", "password").await?;
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
let mut stream = TcpStream::connect(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");
|
||||||
|
|
||||||
|
@ -282,6 +288,7 @@ 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()
|
||||||
|
@ -291,10 +298,10 @@ async fn terminate_socket() -> Result<()> {
|
||||||
));
|
));
|
||||||
|
|
||||||
tracing::info!("Initiating TLS connection...");
|
tracing::info!("Initiating TLS connection...");
|
||||||
let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
|
let mut stream = connector.connect(ServerName::IpAddress(server.addr.ip()), stream).await?;
|
||||||
tracing::info!("TLS connection established");
|
tracing::info!("TLS connection established");
|
||||||
|
|
||||||
server.server.terminate().await?;
|
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);
|
||||||
|
|
||||||
|
|
|
@ -11,15 +11,12 @@ 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);
|
||||||
|
|
||||||
|
|
|
@ -295,9 +295,9 @@ impl ToXml for IqError {
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Debug)]
|
#[derive(PartialEq, Eq, Debug)]
|
||||||
pub struct Iq<T> {
|
pub struct Iq<T> {
|
||||||
pub from: Option<Jid>,
|
pub from: Option<String>,
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub to: Option<Jid>,
|
pub to: Option<String>,
|
||||||
pub r#type: IqType,
|
pub r#type: IqType,
|
||||||
pub body: T,
|
pub body: T,
|
||||||
}
|
}
|
||||||
|
@ -323,9 +323,9 @@ enum IqParserInner<T: FromXml> {
|
||||||
Final(IqParserState<T>),
|
Final(IqParserState<T>),
|
||||||
}
|
}
|
||||||
struct IqParserState<T> {
|
struct IqParserState<T> {
|
||||||
pub from: Option<Jid>,
|
pub from: Option<String>,
|
||||||
pub id: Option<String>,
|
pub id: Option<String>,
|
||||||
pub to: Option<Jid>,
|
pub to: Option<String>,
|
||||||
pub r#type: Option<IqType>,
|
pub r#type: Option<IqType>,
|
||||||
pub body: Option<T>,
|
pub body: Option<T>,
|
||||||
}
|
}
|
||||||
|
@ -348,15 +348,13 @@ impl<T: FromXml> Parser for IqParser<T> {
|
||||||
let attr = fail_fast!(attr);
|
let attr = fail_fast!(attr);
|
||||||
if attr.key.0 == b"from" {
|
if attr.key.0 == b"from" {
|
||||||
let value = fail_fast!(std::str::from_utf8(&*attr.value));
|
let value = fail_fast!(std::str::from_utf8(&*attr.value));
|
||||||
let value = fail_fast!(Jid::from_string(value));
|
state.from = Some(value.to_string())
|
||||||
state.from = Some(value)
|
|
||||||
} else if attr.key.0 == b"id" {
|
} else if attr.key.0 == b"id" {
|
||||||
let value = fail_fast!(std::str::from_utf8(&*attr.value));
|
let value = fail_fast!(std::str::from_utf8(&*attr.value));
|
||||||
state.id = Some(value.to_string())
|
state.id = Some(value.to_string())
|
||||||
} else if attr.key.0 == b"to" {
|
} else if attr.key.0 == b"to" {
|
||||||
let value = fail_fast!(std::str::from_utf8(&*attr.value));
|
let value = fail_fast!(std::str::from_utf8(&*attr.value));
|
||||||
let value = fail_fast!(Jid::from_string(value));
|
state.to = Some(value.to_string())
|
||||||
state.to = Some(value)
|
|
||||||
} else if attr.key.0 == b"type" {
|
} else if attr.key.0 == b"type" {
|
||||||
let value = fail_fast!(IqType::from_str(&*attr.value));
|
let value = fail_fast!(IqType::from_str(&*attr.value));
|
||||||
state.r#type = Some(value);
|
state.r#type = Some(value);
|
||||||
|
@ -433,17 +431,15 @@ impl<T: ToXml> ToXml for Iq<T> {
|
||||||
let mut start = BytesStart::new(start);
|
let mut start = BytesStart::new(start);
|
||||||
let mut attrs = vec![];
|
let mut attrs = vec![];
|
||||||
if let Some(ref from) = self.from {
|
if let Some(ref from) = self.from {
|
||||||
let value = from.to_string().into_bytes();
|
|
||||||
attrs.push(Attribute {
|
attrs.push(Attribute {
|
||||||
key: QName(b"from"),
|
key: QName(b"from"),
|
||||||
value: value.into(),
|
value: from.as_bytes().into(),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
if let Some(ref to) = self.to {
|
if let Some(ref to) = self.to {
|
||||||
let value = to.to_string().into_bytes();
|
|
||||||
attrs.push(Attribute {
|
attrs.push(Attribute {
|
||||||
key: QName(b"to"),
|
key: QName(b"to"),
|
||||||
value: value.into(),
|
value: to.as_bytes().into(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
attrs.push(Attribute {
|
attrs.push(Attribute {
|
||||||
|
|
|
@ -8,12 +8,11 @@ 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. Mind the common name (CN) field, it should match the domain name of the server.
|
Generate self-signed TLS certificate:
|
||||||
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=localhost"
|
-subj "/CN=example.com"
|
||||||
|
|
||||||
Print content of a TLS certificate:
|
Print content of a TLS certificate:
|
||||||
|
|
||||||
|
|
|
@ -19,7 +19,6 @@ 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"
|
||||||
|
|
|
@ -52,7 +52,7 @@ async fn main() -> Result<()> {
|
||||||
let mut metrics = MetricsRegistry::new();
|
let mut metrics = MetricsRegistry::new();
|
||||||
let storage = Storage::open(storage_config).await?;
|
let storage = Storage::open(storage_config).await?;
|
||||||
let rooms = RoomRegistry::new(&mut metrics, storage.clone())?;
|
let rooms = RoomRegistry::new(&mut metrics, storage.clone())?;
|
||||||
let mut players = PlayerRegistry::empty(rooms.clone(), storage.clone(), &mut metrics)?;
|
let mut players = PlayerRegistry::empty(rooms.clone(), &mut metrics)?;
|
||||||
let telemetry_terminator = http::launch(telemetry_config, metrics.clone(), rooms.clone(), storage.clone()).await?;
|
let telemetry_terminator = http::launch(telemetry_config, metrics.clone(), rooms.clone(), storage.clone()).await?;
|
||||||
let irc = projection_irc::launch(
|
let irc = projection_irc::launch(
|
||||||
irc_config,
|
irc_config,
|
||||||
|
|
Loading…
Reference in New Issue