forked from lavina/lavina
Compare commits
No commits in common. "ddb348bee929a3aa7b8d6545a96f5448280b4ce0" and "0b9810258062d95c71ba3678602e754b01d5b947" have entirely different histories.
ddb348bee9
...
0b98102580
|
@ -1,6 +1,6 @@
|
||||||
*
|
*
|
||||||
!/src/
|
!/src/
|
||||||
!/crates/
|
!/migrations/
|
||||||
!Cargo.lock
|
!Cargo.lock
|
||||||
!Cargo.toml
|
!Cargo.toml
|
||||||
!rust-toolchain
|
!rust-toolchain
|
||||||
|
|
|
@ -8,11 +8,6 @@ jobs:
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
- name: setup rust
|
- name: setup rust
|
||||||
uses: https://github.com/actions-rs/toolchain@v1
|
uses: https://github.com/actions-rs/toolchain@v1
|
||||||
- name: check formatting
|
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: fmt
|
|
||||||
args: "--check --all"
|
|
||||||
- name: cargo check
|
- name: cargo check
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
uses: https://github.com/actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
|
@ -21,4 +16,3 @@ jobs:
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
uses: https://github.com/actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: test
|
command: test
|
||||||
args: "--all"
|
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
/target
|
/target
|
||||||
/db.sqlite
|
/db.sqlite
|
||||||
.idea/
|
.idea/
|
||||||
.DS_Store
|
|
||||||
|
|
|
@ -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
|
|
|
@ -1,21 +0,0 @@
|
||||||
<component name="ProjectRunConfigurationManager">
|
|
||||||
<configuration default="false" name="Run lavina" type="CargoCommandRunConfiguration" factoryName="Cargo Command">
|
|
||||||
<option name="command" value="run --package lavina --bin lavina -- --config config.toml" />
|
|
||||||
<option name="workingDirectory" value="file://$PROJECT_DIR$" />
|
|
||||||
<envs>
|
|
||||||
<env name="RUST_LOG" value="debug" />
|
|
||||||
</envs>
|
|
||||||
<option name="emulateTerminal" value="true" />
|
|
||||||
<option name="channel" value="DEFAULT" />
|
|
||||||
<option name="requiredFeatures" value="true" />
|
|
||||||
<option name="allFeatures" value="false" />
|
|
||||||
<option name="withSudo" value="false" />
|
|
||||||
<option name="buildTarget" value="REMOTE" />
|
|
||||||
<option name="backtrace" value="FULL" />
|
|
||||||
<option name="isRedirectInput" value="false" />
|
|
||||||
<option name="redirectInputPath" value="" />
|
|
||||||
<method v="2">
|
|
||||||
<option name="CARGO.BUILD_TASK_PROVIDER" enabled="true" />
|
|
||||||
</method>
|
|
||||||
</configuration>
|
|
||||||
</component>
|
|
File diff suppressed because it is too large
Load Diff
19
Cargo.toml
19
Cargo.toml
|
@ -6,11 +6,10 @@ members = [
|
||||||
"crates/projection-irc",
|
"crates/projection-irc",
|
||||||
"crates/proto-xmpp",
|
"crates/proto-xmpp",
|
||||||
"crates/mgmt-api",
|
"crates/mgmt-api",
|
||||||
"crates/sasl",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.0.2-dev"
|
version = "0.0.1-dev"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
nom = "7.1.3"
|
nom = "7.1.3"
|
||||||
|
@ -18,8 +17,8 @@ assert_matches = "1.5.0"
|
||||||
tokio = { version = "1.24.1", features = ["full"] } # async runtime
|
tokio = { version = "1.24.1", features = ["full"] } # async runtime
|
||||||
futures-util = "0.3.25"
|
futures-util = "0.3.25"
|
||||||
anyhow = "1.0.68" # error utils
|
anyhow = "1.0.68" # error utils
|
||||||
nonempty = "0.10.0"
|
nonempty = "0.8.1"
|
||||||
quick-xml = { version = "0.31.0", features = ["async-tokio"] }
|
quick-xml = { version = "0.30.0", features = ["async-tokio"] }
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
regex = "1.7.1"
|
regex = "1.7.1"
|
||||||
derive_more = "0.99.17"
|
derive_more = "0.99.17"
|
||||||
|
@ -27,10 +26,7 @@ clap = { version = "4.4.4", features = ["derive"] }
|
||||||
serde = { version = "1.0.152", features = ["rc", "serde_derive"] }
|
serde = { version = "1.0.152", features = ["rc", "serde_derive"] }
|
||||||
tracing = "0.1.37" # logging & tracing api
|
tracing = "0.1.37" # logging & tracing api
|
||||||
prometheus = { version = "0.13.3", default-features = false }
|
prometheus = { version = "0.13.3", default-features = false }
|
||||||
base64 = "0.22.0"
|
|
||||||
lavina-core = { path = "crates/lavina-core" }
|
lavina-core = { path = "crates/lavina-core" }
|
||||||
tracing-subscriber = "0.3.16"
|
|
||||||
sasl = { path = "crates/sasl" }
|
|
||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "lavina"
|
name = "lavina"
|
||||||
|
@ -41,14 +37,13 @@ publish = false
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
figment = { version = "0.10.8", features = ["env", "toml"] } # configuration files
|
figment = { version = "0.10.8", features = ["env", "toml"] } # configuration files
|
||||||
hyper = { version = "1.0.1", features = ["server", "http1"] } # http server
|
hyper = { version = "1.0.0-rc.3,<1.0.0-rc.4", features = ["server", "http1"] } # http server
|
||||||
http-body-util = "0.1.0"
|
http-body-util = "0.1.0-rc.3"
|
||||||
hyper-util = { version = "0.1", features = ["server", "http1", "tokio"] }
|
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
serde_json = "1.0.93"
|
serde_json = "1.0.93"
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
tracing-subscriber = "0.3.16"
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
prometheus.workspace = true
|
prometheus.workspace = true
|
||||||
nonempty.workspace = true
|
nonempty.workspace = true
|
||||||
|
@ -62,4 +57,4 @@ clap.workspace = true
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
assert_matches.workspace = true
|
assert_matches.workspace = true
|
||||||
regex = "1.7.1"
|
regex = "1.7.1"
|
||||||
reqwest = { version = "0.12.0", default-features = false }
|
reqwest = { version = "0.11", default-features = false }
|
||||||
|
|
|
@ -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"
|
||||||
|
|
|
@ -0,0 +1,30 @@
|
||||||
|
## Dependency diagram of the project
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
graph TD;
|
||||||
|
lavina-->mgmt-api;
|
||||||
|
lavina-->projection-irc;
|
||||||
|
lavina-->projection-xmpp;
|
||||||
|
lavina-->lavina-core;
|
||||||
|
|
||||||
|
projection-irc-->proto-irc;
|
||||||
|
projection-irc-->lavina-core;
|
||||||
|
|
||||||
|
projection-xmpp-->proto-xmpp;
|
||||||
|
projection-xmpp-->lavina-core;
|
||||||
|
|
||||||
|
sim-irc-->proto-irc;
|
||||||
|
sim-irc-->mgmt-api;
|
||||||
|
|
||||||
|
sim-xmpp-->proto-xmpp;
|
||||||
|
sim-xmpp-->mgmt-api;
|
||||||
|
|
||||||
|
workspace-->lavina;
|
||||||
|
workspace-->sim-irc;
|
||||||
|
workspace-->sim-xmpp;
|
||||||
|
```
|
||||||
|
|
||||||
|
A few rules:
|
||||||
|
- Only projections should be direct deps of `lavina`, there is no need to depend on `proto-*` crates.
|
||||||
|
- On the other hand, projections should not be dependencies of `sim-*` crates.
|
||||||
|
- `lavina-core` does not depend on protocol-specific crates.
|
|
@ -5,9 +5,8 @@ version.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
sqlx = { version = "0.7.4", features = ["sqlite", "migrate"] }
|
sqlx = { version = "0.7.0-alpha.2", features = ["sqlite", "migrate"] }
|
||||||
serde.workspace = true
|
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;
|
|
|
@ -1,11 +1,4 @@
|
||||||
//! Domain definitions and implementation of common chat logic.
|
//! Domain definitions and implementation of common chat logic.
|
||||||
use anyhow::Result;
|
|
||||||
use prometheus::Registry as MetricsRegistry;
|
|
||||||
|
|
||||||
use crate::player::PlayerRegistry;
|
|
||||||
use crate::repo::Storage;
|
|
||||||
use crate::room::RoomRegistry;
|
|
||||||
|
|
||||||
pub mod player;
|
pub mod player;
|
||||||
pub mod prelude;
|
pub mod prelude;
|
||||||
pub mod repo;
|
pub mod repo;
|
||||||
|
@ -13,25 +6,3 @@ pub mod room;
|
||||||
pub mod terminator;
|
pub mod terminator;
|
||||||
|
|
||||||
mod table;
|
mod table;
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct LavinaCore {
|
|
||||||
pub players: PlayerRegistry,
|
|
||||||
pub rooms: RoomRegistry,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LavinaCore {
|
|
||||||
pub async fn new(mut metrics: MetricsRegistry, storage: Storage) -> Result<LavinaCore> {
|
|
||||||
// TODO shutdown all services in reverse order on error
|
|
||||||
let rooms = RoomRegistry::new(&mut metrics, storage.clone())?;
|
|
||||||
let players = PlayerRegistry::empty(rooms.clone(), storage.clone(), &mut metrics)?;
|
|
||||||
Ok(LavinaCore { players, rooms })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn shutdown(mut self) -> Result<()> {
|
|
||||||
self.players.shutdown_all().await?;
|
|
||||||
drop(self.players);
|
|
||||||
drop(self.rooms);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -7,16 +7,19 @@
|
||||||
//!
|
//!
|
||||||
//! 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::{
|
||||||
use tokio::sync::RwLock;
|
sync::mpsc::{channel, Receiver, Sender},
|
||||||
|
task::JoinHandle,
|
||||||
|
};
|
||||||
|
|
||||||
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};
|
||||||
|
|
||||||
|
@ -42,65 +45,58 @@ impl PlayerId {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Node-local identifier of a connection. It is used to address a connection within a player actor.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
pub struct ConnectionId(pub AnonKey);
|
pub struct ConnectionId(pub AnonKey);
|
||||||
|
|
||||||
/// Representation of an authenticated client connection.
|
|
||||||
/// The public API available to projections through which all client actions are executed.
|
|
||||||
///
|
|
||||||
/// The connection is used to send commands to the player actor and to receive updates that might be sent to the client.
|
|
||||||
pub struct PlayerConnection {
|
pub struct PlayerConnection {
|
||||||
pub connection_id: ConnectionId,
|
pub connection_id: ConnectionId,
|
||||||
pub receiver: Receiver<Updates>,
|
pub receiver: Receiver<Updates>,
|
||||||
player_handle: PlayerHandle,
|
player_handle: PlayerHandle,
|
||||||
}
|
}
|
||||||
impl PlayerConnection {
|
impl PlayerConnection {
|
||||||
/// Handled in [Player::send_message].
|
|
||||||
pub async fn send_message(&mut self, room_id: RoomId, body: Str) -> Result<()> {
|
pub async fn send_message(&mut self, room_id: RoomId, body: Str) -> Result<()> {
|
||||||
let (promise, deferred) = oneshot();
|
self.player_handle
|
||||||
let cmd = ClientCommand::SendMessage { room_id, body, promise };
|
.send_message(room_id, self.connection_id.clone(), body)
|
||||||
self.player_handle.send(ActorCommand::ClientCommand(cmd, self.connection_id.clone())).await;
|
.await
|
||||||
Ok(deferred.await?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handled in [Player::join_room].
|
|
||||||
pub async fn join_room(&mut self, room_id: RoomId) -> Result<JoinResult> {
|
pub async fn join_room(&mut self, room_id: RoomId) -> Result<JoinResult> {
|
||||||
let (promise, deferred) = oneshot();
|
self.player_handle.join_room(room_id, self.connection_id.clone()).await
|
||||||
let cmd = ClientCommand::JoinRoom { room_id, promise };
|
|
||||||
self.player_handle.send(ActorCommand::ClientCommand(cmd, self.connection_id.clone())).await;
|
|
||||||
Ok(deferred.await?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handled in [Player::change_topic].
|
|
||||||
pub async fn change_topic(&mut self, room_id: RoomId, new_topic: Str) -> Result<()> {
|
pub async fn change_topic(&mut self, room_id: RoomId, new_topic: Str) -> Result<()> {
|
||||||
let (promise, deferred) = oneshot();
|
let (promise, deferred) = oneshot();
|
||||||
let cmd = ClientCommand::ChangeTopic {
|
let cmd = Cmd::ChangeTopic {
|
||||||
room_id,
|
room_id,
|
||||||
new_topic,
|
new_topic,
|
||||||
promise,
|
promise,
|
||||||
};
|
};
|
||||||
self.player_handle.send(ActorCommand::ClientCommand(cmd, self.connection_id.clone())).await;
|
self.player_handle
|
||||||
|
.send(PlayerCommand::Cmd(cmd, self.connection_id.clone()))
|
||||||
|
.await;
|
||||||
Ok(deferred.await?)
|
Ok(deferred.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handled in [Player::leave_room].
|
|
||||||
pub async fn leave_room(&mut self, room_id: RoomId) -> Result<()> {
|
pub async fn leave_room(&mut self, room_id: RoomId) -> Result<()> {
|
||||||
let (promise, deferred) = oneshot();
|
let (promise, deferred) = oneshot();
|
||||||
let cmd = ClientCommand::LeaveRoom { room_id, promise };
|
self.player_handle
|
||||||
self.player_handle.send(ActorCommand::ClientCommand(cmd, self.connection_id.clone())).await;
|
.send(PlayerCommand::Cmd(
|
||||||
|
Cmd::LeaveRoom { room_id, promise },
|
||||||
|
self.connection_id.clone(),
|
||||||
|
))
|
||||||
|
.await;
|
||||||
Ok(deferred.await?)
|
Ok(deferred.await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn terminate(self) {
|
pub async fn terminate(self) {
|
||||||
self.player_handle.send(ActorCommand::TerminateConnection(self.connection_id)).await;
|
self.player_handle
|
||||||
|
.send(PlayerCommand::TerminateConnection(self.connection_id))
|
||||||
|
.await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handled in [Player::get_rooms].
|
|
||||||
pub async fn get_rooms(&self) -> Result<Vec<RoomInfo>> {
|
pub async fn get_rooms(&self) -> Result<Vec<RoomInfo>> {
|
||||||
let (promise, deferred) = oneshot();
|
let (promise, deferred) = oneshot();
|
||||||
let cmd = ClientCommand::GetRooms { promise };
|
self.player_handle.send(PlayerCommand::GetRooms(promise)).await;
|
||||||
self.player_handle.send(ActorCommand::ClientCommand(cmd, self.connection_id.clone())).await;
|
|
||||||
Ok(deferred.await?)
|
Ok(deferred.await?)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -108,13 +104,13 @@ impl PlayerConnection {
|
||||||
/// Handle to a player actor.
|
/// Handle to a player actor.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct PlayerHandle {
|
pub struct PlayerHandle {
|
||||||
tx: Sender<ActorCommand>,
|
tx: Sender<PlayerCommand>,
|
||||||
}
|
}
|
||||||
impl PlayerHandle {
|
impl PlayerHandle {
|
||||||
pub async fn subscribe(&self) -> PlayerConnection {
|
pub async fn subscribe(&self) -> PlayerConnection {
|
||||||
let (sender, receiver) = channel(32);
|
let (sender, receiver) = channel(32);
|
||||||
let (promise, deferred) = oneshot();
|
let (promise, deferred) = oneshot();
|
||||||
let cmd = ActorCommand::AddConnection { sender, promise };
|
let cmd = PlayerCommand::AddConnection { sender, promise };
|
||||||
let _ = self.tx.send(cmd).await;
|
let _ = self.tx.send(cmd).await;
|
||||||
let connection_id = deferred.await.unwrap();
|
let connection_id = deferred.await.unwrap();
|
||||||
PlayerConnection {
|
PlayerConnection {
|
||||||
|
@ -124,34 +120,45 @@ impl PlayerHandle {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send(&self, command: ActorCommand) {
|
pub async fn send_message(&self, room_id: RoomId, connection_id: ConnectionId, body: Str) -> Result<()> {
|
||||||
// TODO either handle the error or doc why it is safe to ignore
|
let (promise, deferred) = oneshot();
|
||||||
|
let cmd = Cmd::SendMessage { room_id, body, promise };
|
||||||
|
let _ = self.tx.send(PlayerCommand::Cmd(cmd, connection_id)).await;
|
||||||
|
Ok(deferred.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn join_room(&self, room_id: RoomId, connection_id: ConnectionId) -> Result<JoinResult> {
|
||||||
|
let (promise, deferred) = oneshot();
|
||||||
|
let cmd = Cmd::JoinRoom { room_id, promise };
|
||||||
|
let _ = self.tx.send(PlayerCommand::Cmd(cmd, connection_id)).await;
|
||||||
|
Ok(deferred.await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send(&self, command: PlayerCommand) {
|
||||||
let _ = self.tx.send(command).await;
|
let _ = self.tx.send(command).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn update(&self, update: Updates) {
|
pub async fn update(&self, update: Updates) {
|
||||||
self.send(ActorCommand::Update(update)).await;
|
self.send(PlayerCommand::Update(update)).await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Messages sent to the player actor.
|
enum PlayerCommand {
|
||||||
enum ActorCommand {
|
/** Commands from connections */
|
||||||
/// Establish a new connection.
|
|
||||||
AddConnection {
|
AddConnection {
|
||||||
sender: Sender<Updates>,
|
sender: Sender<Updates>,
|
||||||
promise: Promise<ConnectionId>,
|
promise: Promise<ConnectionId>,
|
||||||
},
|
},
|
||||||
/// Terminate an existing connection.
|
|
||||||
TerminateConnection(ConnectionId),
|
TerminateConnection(ConnectionId),
|
||||||
/// Player-issued command.
|
Cmd(Cmd, ConnectionId),
|
||||||
ClientCommand(ClientCommand, ConnectionId),
|
/// Query - responds with a list of rooms the player is a member of.
|
||||||
/// Update which is sent from a room the player is member of.
|
GetRooms(Promise<Vec<RoomInfo>>),
|
||||||
|
/** Events from rooms */
|
||||||
Update(Updates),
|
Update(Updates),
|
||||||
Stop,
|
Stop,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Client-issued command sent to the player actor. The actor will respond with by fulfilling the promise.
|
pub enum Cmd {
|
||||||
pub enum ClientCommand {
|
|
||||||
JoinRoom {
|
JoinRoom {
|
||||||
room_id: RoomId,
|
room_id: RoomId,
|
||||||
promise: Promise<JoinResult>,
|
promise: Promise<JoinResult>,
|
||||||
|
@ -170,14 +177,10 @@ pub enum ClientCommand {
|
||||||
new_topic: Str,
|
new_topic: Str,
|
||||||
promise: Promise<()>,
|
promise: Promise<()>,
|
||||||
},
|
},
|
||||||
GetRooms {
|
|
||||||
promise: Promise<Vec<RoomInfo>>,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum JoinResult {
|
pub enum JoinResult {
|
||||||
Success(RoomInfo),
|
Success(RoomInfo),
|
||||||
AlreadyJoined,
|
|
||||||
Banned,
|
Banned,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -209,43 +212,38 @@ 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(PlayerCommand::Stop).await;
|
||||||
drop(k);
|
drop(k);
|
||||||
j.await?;
|
j.await?;
|
||||||
log::debug!("Player stopped #{i:?}")
|
log::debug!("Player stopped #{i:?}")
|
||||||
|
@ -258,8 +256,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,
|
||||||
}
|
}
|
||||||
|
@ -267,200 +263,152 @@ 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<PlayerCommand>,
|
||||||
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 } => {
|
PlayerCommand::AddConnection { sender, promise } => {
|
||||||
let connection_id = self.connections.insert(sender);
|
let connection_id = self.connections.insert(sender);
|
||||||
if let Err(connection_id) = promise.send(ConnectionId(connection_id)) {
|
if let Err(connection_id) = promise.send(ConnectionId(connection_id)) {
|
||||||
log::warn!("Connection {connection_id:?} terminated before finalization");
|
log::warn!("Connection {connection_id:?} terminated before finalization");
|
||||||
self.terminate_connection(connection_id);
|
self.terminate_connection(connection_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ActorCommand::TerminateConnection(connection_id) => {
|
PlayerCommand::TerminateConnection(connection_id) => {
|
||||||
self.terminate_connection(connection_id);
|
self.terminate_connection(connection_id);
|
||||||
}
|
}
|
||||||
ActorCommand::Update(update) => self.handle_update(update).await,
|
PlayerCommand::GetRooms(promise) => {
|
||||||
ActorCommand::ClientCommand(cmd, connection_id) => self.handle_cmd(cmd, connection_id).await,
|
let mut response = vec![];
|
||||||
ActorCommand::Stop => break,
|
for (_, handle) in &self.my_rooms {
|
||||||
|
response.push(handle.get_room_info().await);
|
||||||
|
}
|
||||||
|
let _ = promise.send(response);
|
||||||
|
}
|
||||||
|
PlayerCommand::Update(update) => {
|
||||||
|
log::info!(
|
||||||
|
"Player received an update, broadcasting to {} connections",
|
||||||
|
self.connections.len()
|
||||||
|
);
|
||||||
|
match update {
|
||||||
|
Updates::BannedFrom(ref room_id) => {
|
||||||
|
self.banned_from.insert(room_id.clone());
|
||||||
|
self.my_rooms.remove(room_id);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
for (_, connection) in &self.connections {
|
||||||
|
let _ = connection.send(update.clone()).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PlayerCommand::Cmd(cmd, connection_id) => self.handle_cmd(cmd, connection_id).await,
|
||||||
|
PlayerCommand::Stop => break,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log::debug!("Shutting down player actor #{:?}", self.player_id);
|
log::debug!("Shutting down player actor #{:?}", self.player_id);
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle an incoming update by changing the internal state and broadcasting it to all connections if necessary.
|
|
||||||
async fn handle_update(&mut self, update: Updates) {
|
|
||||||
log::info!(
|
|
||||||
"Player received an update, broadcasting to {} connections",
|
|
||||||
self.connections.len()
|
|
||||||
);
|
|
||||||
match update {
|
|
||||||
Updates::BannedFrom(ref room_id) => {
|
|
||||||
self.banned_from.insert(room_id.clone());
|
|
||||||
self.my_rooms.remove(room_id);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
for (_, connection) in &self.connections {
|
|
||||||
let _ = connection.send(update.clone()).await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn terminate_connection(&mut self, connection_id: ConnectionId) {
|
fn terminate_connection(&mut self, connection_id: ConnectionId) {
|
||||||
if let None = self.connections.pop(connection_id.0) {
|
if let None = self.connections.pop(connection_id.0) {
|
||||||
log::warn!("Connection {connection_id:?} already terminated");
|
log::warn!("Connection {connection_id:?} already terminated");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Dispatches a client command to the appropriate handler.
|
async fn handle_cmd(&mut self, cmd: Cmd, connection_id: ConnectionId) {
|
||||||
async fn handle_cmd(&mut self, cmd: ClientCommand, connection_id: ConnectionId) {
|
|
||||||
match cmd {
|
match cmd {
|
||||||
ClientCommand::JoinRoom { room_id, promise } => {
|
Cmd::JoinRoom { room_id, promise } => {
|
||||||
let result = self.join_room(connection_id, room_id).await;
|
if self.banned_from.contains(&room_id) {
|
||||||
let _ = promise.send(result);
|
let _ = promise.send(JoinResult::Banned);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let room = match self.rooms.get_or_create_room(room_id.clone()).await {
|
||||||
|
Ok(room) => room,
|
||||||
|
Err(e) => {
|
||||||
|
log::error!("Failed to get or create room: {e}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
room.subscribe(self.player_id.clone(), self.handle.clone()).await;
|
||||||
|
self.my_rooms.insert(room_id.clone(), room.clone());
|
||||||
|
let room_info = room.get_room_info().await;
|
||||||
|
let _ = promise.send(JoinResult::Success(room_info));
|
||||||
|
let update = Updates::RoomJoined {
|
||||||
|
room_id,
|
||||||
|
new_member_id: self.player_id.clone(),
|
||||||
|
};
|
||||||
|
self.broadcast_update(update, connection_id).await;
|
||||||
}
|
}
|
||||||
ClientCommand::LeaveRoom { room_id, promise } => {
|
Cmd::LeaveRoom { room_id, promise } => {
|
||||||
self.leave_room(connection_id, room_id).await;
|
let room = self.my_rooms.remove(&room_id);
|
||||||
|
if let Some(room) = room {
|
||||||
|
room.unsubscribe(&self.player_id).await;
|
||||||
|
let room_info = room.get_room_info().await;
|
||||||
|
}
|
||||||
let _ = promise.send(());
|
let _ = promise.send(());
|
||||||
|
let update = Updates::RoomLeft {
|
||||||
|
room_id,
|
||||||
|
former_member_id: self.player_id.clone(),
|
||||||
|
};
|
||||||
|
self.broadcast_update(update, connection_id).await;
|
||||||
}
|
}
|
||||||
ClientCommand::SendMessage { room_id, body, promise } => {
|
Cmd::SendMessage { room_id, body, promise } => {
|
||||||
self.send_message(connection_id, room_id, body).await;
|
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");
|
||||||
|
}
|
||||||
let _ = promise.send(());
|
let _ = promise.send(());
|
||||||
|
let update = Updates::NewMessage {
|
||||||
|
room_id,
|
||||||
|
author_id: self.player_id.clone(),
|
||||||
|
body,
|
||||||
|
};
|
||||||
|
self.broadcast_update(update, connection_id).await;
|
||||||
}
|
}
|
||||||
ClientCommand::ChangeTopic {
|
Cmd::ChangeTopic {
|
||||||
room_id,
|
room_id,
|
||||||
new_topic,
|
new_topic,
|
||||||
promise,
|
promise,
|
||||||
} => {
|
} => {
|
||||||
self.change_topic(connection_id, room_id, new_topic).await;
|
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");
|
||||||
|
}
|
||||||
let _ = promise.send(());
|
let _ = promise.send(());
|
||||||
}
|
let update = Updates::RoomTopicChanged { room_id, new_topic };
|
||||||
ClientCommand::GetRooms { promise } => {
|
self.broadcast_update(update, connection_id).await;
|
||||||
let result = self.get_rooms().await;
|
|
||||||
let _ = promise.send(result);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn join_room(&mut self, connection_id: ConnectionId, room_id: RoomId) -> JoinResult {
|
|
||||||
if self.banned_from.contains(&room_id) {
|
|
||||||
return JoinResult::Banned;
|
|
||||||
}
|
|
||||||
if self.my_rooms.contains_key(&room_id) {
|
|
||||||
return JoinResult::AlreadyJoined;
|
|
||||||
}
|
|
||||||
|
|
||||||
let room = match self.rooms.get_or_create_room(room_id.clone()).await {
|
|
||||||
Ok(room) => room,
|
|
||||||
Err(e) => {
|
|
||||||
log::error!("Failed to get or create room: {e}");
|
|
||||||
todo!();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
room.add_member(&self.player_id, self.storage_id).await;
|
|
||||||
room.subscribe(&self.player_id, self.handle.clone()).await;
|
|
||||||
self.my_rooms.insert(room_id.clone(), room.clone());
|
|
||||||
let room_info = room.get_room_info().await;
|
|
||||||
let update = Updates::RoomJoined {
|
|
||||||
room_id,
|
|
||||||
new_member_id: self.player_id.clone(),
|
|
||||||
};
|
|
||||||
self.broadcast_update(update, connection_id).await;
|
|
||||||
JoinResult::Success(room_info)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn leave_room(&mut self, connection_id: ConnectionId, room_id: RoomId) {
|
|
||||||
let room = self.my_rooms.remove(&room_id);
|
|
||||||
if let Some(room) = room {
|
|
||||||
room.unsubscribe(&self.player_id).await;
|
|
||||||
room.remove_member(&self.player_id, self.storage_id).await;
|
|
||||||
}
|
|
||||||
let update = Updates::RoomLeft {
|
|
||||||
room_id,
|
|
||||||
former_member_id: self.player_id.clone(),
|
|
||||||
};
|
|
||||||
self.broadcast_update(update, connection_id).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send_message(&mut self, connection_id: ConnectionId, room_id: RoomId, body: Str) {
|
|
||||||
let Some(room) = self.my_rooms.get(&room_id) else {
|
|
||||||
tracing::info!("no room found");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
room.send_message(&self.player_id, body.clone()).await;
|
|
||||||
let update = Updates::NewMessage {
|
|
||||||
room_id,
|
|
||||||
author_id: self.player_id.clone(),
|
|
||||||
body,
|
|
||||||
};
|
|
||||||
self.broadcast_update(update, connection_id).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
tracing::info!("no room found");
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
room.set_topic(&self.player_id, new_topic.clone()).await;
|
|
||||||
let update = Updates::RoomTopicChanged { room_id, new_topic };
|
|
||||||
self.broadcast_update(update, connection_id).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_rooms(&self) -> Vec<RoomInfo> {
|
|
||||||
let mut response = vec![];
|
|
||||||
for (_, handle) in &self.my_rooms {
|
|
||||||
response.push(handle.get_room_info().await);
|
|
||||||
}
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Broadcasts an update to all connections except the one with the given id.
|
|
||||||
///
|
|
||||||
/// This is called after handling a client command.
|
|
||||||
/// Sending the update to the connection which sent the command is handled by the connection itself.
|
|
||||||
async fn broadcast_update(&self, update: Updates, except: ConnectionId) {
|
async fn broadcast_update(&self, update: Updates, except: ConnectionId) {
|
||||||
for (a, b) in &self.connections {
|
for (a, b) in &self.connections {
|
||||||
if ConnectionId(a) == except {
|
if ConnectionId(a) == except {
|
||||||
|
|
|
@ -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};
|
||||||
|
@ -32,7 +31,7 @@ impl RoomId {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Shared data structure for storing metadata about rooms.
|
/// Shared datastructure for storing metadata about rooms.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RoomRegistry(Arc<AsyncRwLock<RoomRegistryInner>>);
|
pub struct RoomRegistry(Arc<AsyncRwLock<RoomRegistryInner>>);
|
||||||
impl RoomRegistry {
|
impl RoomRegistry {
|
||||||
|
@ -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,51 +148,51 @@ 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Room {
|
struct Room {
|
||||||
/// The numeric node-local id of the room as it is stored in the database.
|
|
||||||
storage_id: u32,
|
storage_id: u32,
|
||||||
/// The cluster-global id of the room.
|
|
||||||
room_id: RoomId,
|
room_id: RoomId,
|
||||||
/// 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.
|
|
||||||
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;
|
||||||
let update = Updates::NewMessage {
|
let update = Updates::NewMessage {
|
||||||
room_id: self.room_id.clone(),
|
room_id: self.room_id.clone(),
|
||||||
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(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Broadcasts an update to all players except the one who caused the update.
|
|
||||||
///
|
|
||||||
/// This is called after handling a client command.
|
|
||||||
/// Sending the update to the player who sent the command is handled by the player actor.
|
|
||||||
async fn broadcast_update(&self, update: Updates, except: &PlayerId) {
|
async fn broadcast_update(&self, update: Updates, except: &PlayerId) {
|
||||||
tracing::debug!("Broadcasting an update to {} subs", self.subscriptions.len());
|
tracing::debug!("Broadcasting an update to {} subs", self.subscriptions.len());
|
||||||
for (player_id, sub) in &self.subscriptions {
|
for (player_id, sub) in &self.subscriptions {
|
||||||
|
|
|
@ -11,10 +11,6 @@ serde.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
prometheus.workspace = true
|
prometheus.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
nonempty.workspace = true
|
|
||||||
bitflags = "2.4.1"
|
|
||||||
proto-irc = { path = "../proto-irc" }
|
|
||||||
sasl = { path = "../sasl" }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
nonempty.workspace = true
|
||||||
tracing-subscriber.workspace = true
|
proto-irc = { path = "../proto-irc" }
|
||||||
|
|
|
@ -1,9 +0,0 @@
|
||||||
use bitflags::bitflags;
|
|
||||||
|
|
||||||
bitflags! {
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Capabilities: u32 {
|
|
||||||
const None = 0;
|
|
||||||
const Sasl = 1 << 0;
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -7,7 +7,6 @@ use nonempty::nonempty;
|
||||||
use nonempty::NonEmpty;
|
use nonempty::NonEmpty;
|
||||||
use prometheus::{IntCounter, IntGauge, Registry as MetricsRegistry};
|
use prometheus::{IntCounter, IntGauge, Registry as MetricsRegistry};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use tokio::io::AsyncReadExt;
|
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
|
use tokio::io::{AsyncBufReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter};
|
||||||
use tokio::net::tcp::{ReadHalf, WriteHalf};
|
use tokio::net::tcp::{ReadHalf, WriteHalf};
|
||||||
use tokio::net::{TcpListener, TcpStream};
|
use tokio::net::{TcpListener, TcpStream};
|
||||||
|
@ -18,20 +17,10 @@ use lavina_core::prelude::*;
|
||||||
use lavina_core::repo::Storage;
|
use lavina_core::repo::Storage;
|
||||||
use lavina_core::room::{RoomId, RoomInfo, RoomRegistry};
|
use lavina_core::room::{RoomId, RoomInfo, RoomRegistry};
|
||||||
use lavina_core::terminator::Terminator;
|
use lavina_core::terminator::Terminator;
|
||||||
use lavina_core::LavinaCore;
|
|
||||||
use proto_irc::client::CapabilitySubcommand;
|
|
||||||
use proto_irc::client::{client_message, ClientMessage};
|
use proto_irc::client::{client_message, ClientMessage};
|
||||||
use proto_irc::server::CapSubBody;
|
|
||||||
use proto_irc::server::{AwayStatus, ServerMessage, ServerMessageBody};
|
use proto_irc::server::{AwayStatus, ServerMessage, ServerMessageBody};
|
||||||
use proto_irc::user::PrefixedNick;
|
use proto_irc::user::PrefixedNick;
|
||||||
use proto_irc::{Chan, Recipient};
|
use proto_irc::{Chan, Recipient};
|
||||||
use sasl::AuthBody;
|
|
||||||
|
|
||||||
mod cap;
|
|
||||||
|
|
||||||
use crate::cap::Capabilities;
|
|
||||||
|
|
||||||
pub const APP_VERSION: &str = concat!("lavina", "_", env!("CARGO_PKG_VERSION"));
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
pub struct ServerConfig {
|
pub struct ServerConfig {
|
||||||
|
@ -45,7 +34,7 @@ struct RegisteredUser {
|
||||||
/**
|
/**
|
||||||
* Username is mostly unused in modern IRC.
|
* Username is mostly unused in modern IRC.
|
||||||
*
|
*
|
||||||
* <https://stackoverflow.com/questions/31666247/what-is-the-difference-between-the-nick-username-and-real-name-in-irc-and-wha>
|
* [https://stackoverflow.com/questions/31666247/what-is-the-difference-between-the-nick-username-and-real-name-in-irc-and-wha]
|
||||||
*/
|
*/
|
||||||
username: Str,
|
username: Str,
|
||||||
realname: Str,
|
realname: Str,
|
||||||
|
@ -55,7 +44,8 @@ async fn handle_socket(
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
mut stream: TcpStream,
|
mut stream: TcpStream,
|
||||||
socket_addr: &SocketAddr,
|
socket_addr: &SocketAddr,
|
||||||
mut core: LavinaCore,
|
players: PlayerRegistry,
|
||||||
|
rooms: RoomRegistry,
|
||||||
termination: Deferred<()>, // TODO use it to stop the connection gracefully
|
termination: Deferred<()>, // TODO use it to stop the connection gracefully
|
||||||
mut storage: Storage,
|
mut storage: Storage,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
@ -64,346 +54,126 @@ async fn handle_socket(
|
||||||
let mut reader: BufReader<ReadHalf> = BufReader::new(reader);
|
let mut reader: BufReader<ReadHalf> = BufReader::new(reader);
|
||||||
let mut writer = BufWriter::new(writer);
|
let mut writer = BufWriter::new(writer);
|
||||||
|
|
||||||
pin!(termination);
|
ServerMessage {
|
||||||
select! {
|
tags: vec![],
|
||||||
biased;
|
sender: Some(config.server_name.clone().into()),
|
||||||
_ = &mut termination =>{
|
body: ServerMessageBody::Notice {
|
||||||
log::info!("Socket handling was terminated");
|
first_target: "*".into(),
|
||||||
return Ok(())
|
rest_targets: vec![],
|
||||||
|
text: "Welcome to my server!".into(),
|
||||||
},
|
},
|
||||||
registered_user = handle_registration(&mut reader, &mut writer, &mut storage, &config) =>
|
|
||||||
match registered_user {
|
|
||||||
Ok(user) => {
|
|
||||||
log::debug!("User registered");
|
|
||||||
handle_registered_socket(config, core.players, core.rooms, &mut reader, &mut writer, user).await?;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
log::debug!("Registration failed: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
.write_async(&mut writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
|
|
||||||
|
let registered_user: Result<RegisteredUser> = handle_registration(&mut reader, &mut writer, &mut storage).await;
|
||||||
|
|
||||||
|
match registered_user {
|
||||||
|
Ok(user) => {
|
||||||
|
log::debug!("User registered");
|
||||||
|
handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user).await?;
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
log::debug!("Registration failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
stream.shutdown().await?;
|
stream.shutdown().await?;
|
||||||
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>>,
|
||||||
storage: &mut Storage,
|
storage: &mut Storage,
|
||||||
config: &ServerConfig,
|
|
||||||
) -> 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 pass: Option<Str> = None;
|
||||||
|
|
||||||
let user = loop {
|
let user = loop {
|
||||||
let res = read_irc_message(reader, &mut buffer).await;
|
let res = reader.read_until(b'\n', &mut buffer).await;
|
||||||
tracing::trace!("Received message: {:?}", res);
|
let res = match res {
|
||||||
let len = match res {
|
Ok(len) => {
|
||||||
Ok(len) => len,
|
if len == 0 {
|
||||||
|
log::info!("Terminating socket");
|
||||||
|
break Err(anyhow::Error::msg("EOF"));
|
||||||
|
}
|
||||||
|
match std::str::from_utf8(&buffer[..len]) {
|
||||||
|
Ok(res) => res,
|
||||||
|
Err(e) => break Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
log::warn!("Failed to read from socket: {err}");
|
log::warn!("Failed to read from socket: {err}");
|
||||||
break Err(err.into());
|
break Err(err.into());
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if len == 0 {
|
log::debug!("Incoming raw IRC message: '{res}'");
|
||||||
log::info!("Terminating socket");
|
|
||||||
break Err(anyhow::Error::msg("EOF"));
|
|
||||||
}
|
|
||||||
let res = match std::str::from_utf8(&buffer[..len - 2]) {
|
|
||||||
Ok(res) => res,
|
|
||||||
Err(e) => break Err(e.into()),
|
|
||||||
};
|
|
||||||
tracing::trace!("Incoming raw IRC message: '{res}'");
|
|
||||||
let parsed = client_message(res);
|
let parsed = client_message(res);
|
||||||
let msg = match parsed {
|
match parsed {
|
||||||
Ok(msg) => msg,
|
Ok((_, msg)) => {
|
||||||
Err(err) => {
|
log::debug!("Incoming IRC message: {msg:?}");
|
||||||
tracing::warn!("Failed to parse IRC message: {err}");
|
match msg {
|
||||||
buffer.clear();
|
ClientMessage::Pass { password } => {
|
||||||
continue;
|
pass = Some(password);
|
||||||
|
}
|
||||||
|
ClientMessage::Nick { nickname } => {
|
||||||
|
if let Some((username, realname)) = future_username {
|
||||||
|
break Ok(RegisteredUser {
|
||||||
|
nickname,
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
future_nickname = Some(nickname);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ClientMessage::User { username, realname } => {
|
||||||
|
if let Some(nickname) = future_nickname {
|
||||||
|
break Ok(RegisteredUser {
|
||||||
|
nickname,
|
||||||
|
username,
|
||||||
|
realname,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
future_username = Some((username, realname));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
log::warn!("Failed to parse IRC message: {err}");
|
||||||
}
|
}
|
||||||
};
|
|
||||||
tracing::debug!("Incoming IRC message: {msg:?}");
|
|
||||||
if let Some(user) = state.handle_msg(msg, writer, storage, config).await? {
|
|
||||||
break Ok(user);
|
|
||||||
}
|
}
|
||||||
buffer.clear();
|
buffer.clear();
|
||||||
}?;
|
}?;
|
||||||
// TODO properly implement session temination
|
|
||||||
Ok(user)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sasl_fail_message(sender: Str, nick: Str, text: Str) -> ServerMessage {
|
let stored_user = storage.retrieve_user_by_name(&*user.nickname).await?;
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(sender),
|
|
||||||
body: ServerMessageBody::N904SaslFail { nick, text },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn auth_user(storage: &mut Storage, login: &str, plain_password: &str) -> Result<()> {
|
|
||||||
let stored_user = storage.retrieve_user_by_name(login).await?;
|
|
||||||
|
|
||||||
let stored_user = match stored_user {
|
let stored_user = match stored_user {
|
||||||
Some(u) => u,
|
Some(u) => u,
|
||||||
None => {
|
None => {
|
||||||
log::info!("User '{}' not found", login);
|
log::info!("User '{}' not found", user.nickname);
|
||||||
return Err(anyhow!("no user found"));
|
return Err(anyhow!("no user found"));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let Some(expected_password) = stored_user.password else {
|
if stored_user.password.is_none() {
|
||||||
log::info!("Password not defined for user '{}'", login);
|
log::info!("Password not defined for user '{}'", user.nickname);
|
||||||
return Err(anyhow!("password is not defined"));
|
return Err(anyhow!("password is not defined"));
|
||||||
};
|
}
|
||||||
if expected_password != plain_password {
|
if stored_user.password.as_deref() != pass.as_deref() {
|
||||||
log::info!("Incorrect password supplied for user '{}'", login);
|
log::info!("Incorrect password supplied for user '{}'", user.nickname);
|
||||||
return Err(anyhow!("passwords do not match"));
|
return Err(anyhow!("passwords do not match"));
|
||||||
}
|
}
|
||||||
Ok(())
|
// TODO properly implement session temination
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_registered_socket<'a>(
|
async fn handle_registered_socket<'a>(
|
||||||
|
@ -418,15 +188,14 @@ 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();
|
|
||||||
|
|
||||||
ServerMessage {
|
ServerMessage {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
sender: Some(config.server_name.clone()),
|
sender: Some(config.server_name.clone()),
|
||||||
body: ServerMessageBody::N001Welcome {
|
body: ServerMessageBody::N001Welcome {
|
||||||
client: user.nickname.clone(),
|
client: user.nickname.clone(),
|
||||||
text: text.clone(),
|
text: "Welcome to Kek Server".into(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
.write_async(writer)
|
.write_async(writer)
|
||||||
|
@ -436,7 +205,7 @@ async fn handle_registered_socket<'a>(
|
||||||
sender: Some(config.server_name.clone()),
|
sender: Some(config.server_name.clone()),
|
||||||
body: ServerMessageBody::N002YourHost {
|
body: ServerMessageBody::N002YourHost {
|
||||||
client: user.nickname.clone(),
|
client: user.nickname.clone(),
|
||||||
text: text.clone(),
|
text: "Welcome to Kek Server".into(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
.write_async(writer)
|
.write_async(writer)
|
||||||
|
@ -446,7 +215,7 @@ async fn handle_registered_socket<'a>(
|
||||||
sender: Some(config.server_name.clone()),
|
sender: Some(config.server_name.clone()),
|
||||||
body: ServerMessageBody::N003Created {
|
body: ServerMessageBody::N003Created {
|
||||||
client: user.nickname.clone(),
|
client: user.nickname.clone(),
|
||||||
text: text.clone(),
|
text: "Welcome to Kek Server".into(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
.write_async(writer)
|
.write_async(writer)
|
||||||
|
@ -457,7 +226,7 @@ async fn handle_registered_socket<'a>(
|
||||||
body: ServerMessageBody::N004MyInfo {
|
body: ServerMessageBody::N004MyInfo {
|
||||||
client: user.nickname.clone(),
|
client: user.nickname.clone(),
|
||||||
hostname: config.server_name.clone(),
|
hostname: config.server_name.clone(),
|
||||||
softname: APP_VERSION.into(),
|
softname: "kek-0.1.alpha.3".into(),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
.write_async(writer)
|
.write_async(writer)
|
||||||
|
@ -483,7 +252,7 @@ async fn handle_registered_socket<'a>(
|
||||||
loop {
|
loop {
|
||||||
select! {
|
select! {
|
||||||
biased;
|
biased;
|
||||||
len = read_irc_message(reader, &mut buffer) => {
|
len = reader.read_until(b'\n', &mut buffer) => {
|
||||||
let len = len?;
|
let len = len?;
|
||||||
let len = if len == 0 {
|
let len = if len == 0 {
|
||||||
log::info!("EOF, Terminating socket");
|
log::info!("EOF, Terminating socket");
|
||||||
|
@ -491,7 +260,7 @@ async fn handle_registered_socket<'a>(
|
||||||
} else {
|
} else {
|
||||||
len
|
len
|
||||||
};
|
};
|
||||||
let incoming = std::str::from_utf8(&buffer[0..len-2])?;
|
let incoming = std::str::from_utf8(&buffer[0..len])?;
|
||||||
if let HandleResult::Leave = handle_incoming_message(incoming, &config, &user, &rooms, &mut connection, writer).await? {
|
if let HandleResult::Leave = handle_incoming_message(incoming, &config, &user, &rooms, &mut connection, writer).await? {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -522,23 +291,6 @@ async fn handle_registered_socket<'a>(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO this is public only for tests, perhaps move this into proto-irc
|
|
||||||
// TODO limit buffer size in size to protect against dos attacks with large payloads
|
|
||||||
pub async fn read_irc_message(reader: &mut BufReader<ReadHalf<'_>>, buf: &mut Vec<u8>) -> Result<usize> {
|
|
||||||
let mut size = 0;
|
|
||||||
'outer: loop {
|
|
||||||
let res = reader.read_until(b'\r', buf).await?;
|
|
||||||
size += res;
|
|
||||||
let next = reader.read_u8().await?;
|
|
||||||
buf.push(next);
|
|
||||||
size += 1;
|
|
||||||
if next != b'\n' {
|
|
||||||
continue 'outer;
|
|
||||||
}
|
|
||||||
return Ok(size);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_update(
|
async fn handle_update(
|
||||||
config: &ServerConfig,
|
config: &ServerConfig,
|
||||||
user: &RegisteredUser,
|
user: &RegisteredUser,
|
||||||
|
@ -646,7 +398,7 @@ async fn handle_incoming_message(
|
||||||
let parsed = client_message(buffer);
|
let parsed = client_message(buffer);
|
||||||
log::debug!("Incoming IRC message: {parsed:?}");
|
log::debug!("Incoming IRC message: {parsed:?}");
|
||||||
match parsed {
|
match parsed {
|
||||||
Ok(msg) => match msg {
|
Ok((_, msg)) => match msg {
|
||||||
ClientMessage::Ping { token } => {
|
ClientMessage::Ping { token } => {
|
||||||
ServerMessage {
|
ServerMessage {
|
||||||
tags: vec![],
|
tags: vec![],
|
||||||
|
@ -900,8 +652,11 @@ async fn produce_on_join_cmd_messages(
|
||||||
}
|
}
|
||||||
.write_async(writer)
|
.write_async(writer)
|
||||||
.await?;
|
.await?;
|
||||||
let prefixed_members: Vec<PrefixedNick> =
|
let prefixed_members: Vec<PrefixedNick> = room_info
|
||||||
room_info.members.iter().map(|member| PrefixedNick::from_str(member.clone().into_inner())).collect();
|
.members
|
||||||
|
.iter()
|
||||||
|
.map(|member| PrefixedNick::from_str(member.clone().into_inner()))
|
||||||
|
.collect();
|
||||||
let non_empty_members: NonEmpty<PrefixedNick> =
|
let non_empty_members: NonEmpty<PrefixedNick> =
|
||||||
NonEmpty::from_vec(prefixed_members).unwrap_or(nonempty![PrefixedNick::from_str(user.nickname.clone())]);
|
NonEmpty::from_vec(prefixed_members).unwrap_or(nonempty![PrefixedNick::from_str(user.nickname.clone())]);
|
||||||
|
|
||||||
|
@ -929,23 +684,13 @@ async fn produce_on_join_cmd_messages(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct RunningServer {
|
|
||||||
pub addr: SocketAddr,
|
|
||||||
terminator: Terminator,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RunningServer {
|
|
||||||
pub async fn terminate(self) -> Result<()> {
|
|
||||||
self.terminator.terminate().await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn launch(
|
pub async fn launch(
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
core: LavinaCore,
|
players: PlayerRegistry,
|
||||||
|
rooms: RoomRegistry,
|
||||||
metrics: MetricsRegistry,
|
metrics: MetricsRegistry,
|
||||||
storage: Storage,
|
storage: Storage,
|
||||||
) -> Result<RunningServer> {
|
) -> Result<Terminator> {
|
||||||
log::info!("Starting IRC projection");
|
log::info!("Starting IRC projection");
|
||||||
let (stopped_tx, mut stopped_rx) = channel(32);
|
let (stopped_tx, mut stopped_rx) = channel(32);
|
||||||
let current_connections = IntGauge::new("irc_current_connections", "Open and alive TCP connections")?;
|
let current_connections = IntGauge::new("irc_current_connections", "Open and alive TCP connections")?;
|
||||||
|
@ -954,7 +699,6 @@ pub async fn launch(
|
||||||
metrics.register(Box::new(total_connections.clone()))?;
|
metrics.register(Box::new(total_connections.clone()))?;
|
||||||
|
|
||||||
let listener = TcpListener::bind(config.listen_on).await?;
|
let listener = TcpListener::bind(config.listen_on).await?;
|
||||||
let addr = listener.local_addr()?;
|
|
||||||
|
|
||||||
let terminator = Terminator::spawn(|mut rx| async move {
|
let terminator = Terminator::spawn(|mut rx| async move {
|
||||||
// TODO probably should separate logic for accepting new connection and storing them
|
// TODO probably should separate logic for accepting new connection and storing them
|
||||||
|
@ -983,12 +727,13 @@ pub async fn launch(
|
||||||
}
|
}
|
||||||
|
|
||||||
let terminator = Terminator::spawn(|termination| {
|
let terminator = Terminator::spawn(|termination| {
|
||||||
let core = core.clone();
|
let players = players.clone();
|
||||||
|
let rooms = rooms.clone();
|
||||||
let current_connections_clone = current_connections.clone();
|
let current_connections_clone = current_connections.clone();
|
||||||
let stopped_tx = stopped_tx.clone();
|
let stopped_tx = stopped_tx.clone();
|
||||||
let storage = storage.clone();
|
let storage = storage.clone();
|
||||||
async move {
|
async move {
|
||||||
match handle_socket(config, stream, &socket_addr, core, termination, storage).await {
|
match handle_socket(config, stream, &socket_addr, players, rooms, termination, storage).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}"),
|
||||||
}
|
}
|
||||||
|
@ -1021,5 +766,5 @@ pub async fn launch(
|
||||||
});
|
});
|
||||||
|
|
||||||
log::info!("Started IRC projection");
|
log::info!("Started IRC projection");
|
||||||
Ok(RunningServer { addr, terminator })
|
Ok(terminator)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,560 +0,0 @@
|
||||||
use std::io::ErrorKind;
|
|
||||||
use std::net::SocketAddr;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
use prometheus::Registry as MetricsRegistry;
|
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
|
|
||||||
use tokio::net::tcp::{ReadHalf, WriteHalf};
|
|
||||||
use tokio::net::TcpStream;
|
|
||||||
|
|
||||||
use lavina_core::repo::{Storage, StorageConfig};
|
|
||||||
use lavina_core::LavinaCore;
|
|
||||||
use projection_irc::APP_VERSION;
|
|
||||||
use projection_irc::{launch, read_irc_message, RunningServer, ServerConfig};
|
|
||||||
struct TestScope<'a> {
|
|
||||||
reader: BufReader<ReadHalf<'a>>,
|
|
||||||
writer: WriteHalf<'a>,
|
|
||||||
buffer: Vec<u8>,
|
|
||||||
pub timeout: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TestScope<'a> {
|
|
||||||
fn new(stream: &mut TcpStream) -> TestScope<'_> {
|
|
||||||
let (reader, writer) = stream.split();
|
|
||||||
let reader = BufReader::new(reader);
|
|
||||||
let buffer = vec![];
|
|
||||||
let timeout = Duration::from_millis(100);
|
|
||||||
TestScope {
|
|
||||||
reader,
|
|
||||||
writer,
|
|
||||||
buffer,
|
|
||||||
timeout,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send(&mut self, str: &(impl AsRef<str> + ?Sized)) -> Result<()> {
|
|
||||||
self.writer.write_all(str.as_ref().as_bytes()).await?;
|
|
||||||
self.writer.write_all(b"\r\n").await?;
|
|
||||||
self.writer.flush().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn expect(&mut self, str: &str) -> Result<()> {
|
|
||||||
tracing::debug!("Expecting {}", str);
|
|
||||||
let len = tokio::time::timeout(self.timeout, read_irc_message(&mut self.reader, &mut self.buffer)).await??;
|
|
||||||
assert_eq!(std::str::from_utf8(&self.buffer[..len - 2])?, str);
|
|
||||||
self.buffer.clear();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn expect_that(&mut self, validate: impl FnOnce(&str) -> bool) -> Result<()> {
|
|
||||||
let len = tokio::time::timeout(self.timeout, read_irc_message(&mut self.reader, &mut self.buffer)).await??;
|
|
||||||
let msg = std::str::from_utf8(&self.buffer[..len - 2])?;
|
|
||||||
if !validate(msg) {
|
|
||||||
return Err(anyhow!("unexpected message: {:?}", msg));
|
|
||||||
}
|
|
||||||
self.buffer.clear();
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn expect_server_introduction(&mut self, nick: &str) -> Result<()> {
|
|
||||||
self.expect(&format!(":testserver 001 {nick} :Welcome to testserver Server")).await?;
|
|
||||||
self.expect(&format!(":testserver 002 {nick} :Welcome to testserver Server")).await?;
|
|
||||||
self.expect(&format!(":testserver 003 {nick} :Welcome to testserver Server")).await?;
|
|
||||||
self.expect(&format!(
|
|
||||||
":testserver 004 {nick} testserver {APP_VERSION} r CFILPQbcefgijklmnopqrstvz"
|
|
||||||
))
|
|
||||||
.await?;
|
|
||||||
self.expect(&format!(
|
|
||||||
":testserver 005 {nick} CHANTYPES=# :are supported by this server"
|
|
||||||
))
|
|
||||||
.await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn expect_eof(&mut self) -> Result<()> {
|
|
||||||
let mut buf = [0; 1];
|
|
||||||
let len = tokio::time::timeout(self.timeout, self.reader.read(&mut buf)).await??;
|
|
||||||
if len != 0 {
|
|
||||||
return Err(anyhow!("not a eof"));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn expect_nothing(&mut self) -> Result<()> {
|
|
||||||
let mut buf = [0; 1];
|
|
||||||
match tokio::time::timeout(self.timeout, self.reader.read(&mut buf)).await {
|
|
||||||
Ok(res) => Err(anyhow!("received something: {:?}", res)),
|
|
||||||
Err(_) => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestServer {
|
|
||||||
metrics: MetricsRegistry,
|
|
||||||
storage: Storage,
|
|
||||||
core: LavinaCore,
|
|
||||||
server: RunningServer,
|
|
||||||
}
|
|
||||||
impl TestServer {
|
|
||||||
async fn start() -> Result<TestServer> {
|
|
||||||
let _ = tracing_subscriber::fmt::try_init();
|
|
||||||
let config = ServerConfig {
|
|
||||||
listen_on: "127.0.0.1:0".parse().unwrap(),
|
|
||||||
server_name: "testserver".into(),
|
|
||||||
};
|
|
||||||
let mut metrics = MetricsRegistry::new();
|
|
||||||
let mut storage = Storage::open(StorageConfig {
|
|
||||||
db_path: ":memory:".into(),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
let core = LavinaCore::new(metrics.clone(), storage.clone()).await?;
|
|
||||||
let server = launch(config, core.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
|
||||||
Ok(TestServer {
|
|
||||||
metrics,
|
|
||||||
storage,
|
|
||||||
core,
|
|
||||||
server,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn reboot(self) -> Result<TestServer> {
|
|
||||||
let config = ServerConfig {
|
|
||||||
listen_on: "127.0.0.1:0".parse().unwrap(),
|
|
||||||
server_name: "testserver".into(),
|
|
||||||
};
|
|
||||||
let TestServer {
|
|
||||||
metrics: _,
|
|
||||||
storage,
|
|
||||||
mut core,
|
|
||||||
server,
|
|
||||||
} = self;
|
|
||||||
server.terminate().await?;
|
|
||||||
core.shutdown().await?;
|
|
||||||
let metrics = MetricsRegistry::new();
|
|
||||||
let core = LavinaCore::new(metrics.clone(), storage.clone()).await?;
|
|
||||||
let server = launch(config, core.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
|
||||||
Ok(TestServer {
|
|
||||||
metrics,
|
|
||||||
storage,
|
|
||||||
core,
|
|
||||||
server,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_basic() -> 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("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("QUIT :Leaving").await?;
|
|
||||||
s.expect(":testserver ERROR :Leaving the server").await?;
|
|
||||||
s.expect_eof().await?;
|
|
||||||
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// wrap up
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_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]
|
|
||||||
async fn scenario_force_join_msg() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
|
||||||
server.storage.set_password("tester", "password").await?;
|
|
||||||
|
|
||||||
let mut stream1 = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s1 = TestScope::new(&mut stream1);
|
|
||||||
let mut stream2 = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s2 = TestScope::new(&mut stream2);
|
|
||||||
|
|
||||||
s1.send("PASS password").await?;
|
|
||||||
s1.send("NICK tester").await?;
|
|
||||||
s1.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s1.expect_server_introduction("tester").await?;
|
|
||||||
s1.expect_nothing().await?;
|
|
||||||
|
|
||||||
s2.send("PASS password").await?;
|
|
||||||
s2.send("NICK tester").await?;
|
|
||||||
s2.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s2.expect_server_introduction("tester").await?;
|
|
||||||
s2.expect_nothing().await?;
|
|
||||||
|
|
||||||
// We join the channel from the first connection
|
|
||||||
s1.send("JOIN #test").await?;
|
|
||||||
s1.expect(":tester JOIN #test").await?;
|
|
||||||
s1.expect(":testserver 332 tester #test :New room").await?;
|
|
||||||
s1.expect(":testserver 353 tester = #test :tester").await?;
|
|
||||||
s1.expect(":testserver 366 tester #test :End of /NAMES list").await?;
|
|
||||||
|
|
||||||
// And the second connection should receive the JOIN message (forced JOIN)
|
|
||||||
s2.expect(":tester JOIN #test").await?;
|
|
||||||
s2.expect(":testserver 332 tester #test :New room").await?;
|
|
||||||
s2.expect(":testserver 353 tester = #test :tester").await?;
|
|
||||||
s2.expect(":testserver 366 tester #test :End of /NAMES list").await?;
|
|
||||||
|
|
||||||
// We send a message to the channel from the second connection
|
|
||||||
s2.send("PRIVMSG #test :Hello").await?;
|
|
||||||
// We should not receive an acknowledgement from the server
|
|
||||||
s2.expect_nothing().await?;
|
|
||||||
// But we should receive this message from the first connection
|
|
||||||
s1.expect(":tester PRIVMSG #test :Hello").await?;
|
|
||||||
|
|
||||||
s1.send("QUIT :Leaving").await?;
|
|
||||||
s1.expect(":testserver ERROR :Leaving the server").await?;
|
|
||||||
s1.expect_eof().await?;
|
|
||||||
|
|
||||||
// Closing a connection does not kick you from the channel on a different connection
|
|
||||||
s2.expect_nothing().await?;
|
|
||||||
|
|
||||||
s2.send("QUIT :Leaving").await?;
|
|
||||||
s2.expect(":testserver ERROR :Leaving the server").await?;
|
|
||||||
s2.expect_eof().await?;
|
|
||||||
|
|
||||||
stream1.shutdown().await?;
|
|
||||||
stream2.shutdown().await?;
|
|
||||||
|
|
||||||
// wrap up
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_two_users() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
server.storage.create_user("tester1").await?;
|
|
||||||
server.storage.set_password("tester1", "password").await?;
|
|
||||||
server.storage.create_user("tester2").await?;
|
|
||||||
server.storage.set_password("tester2", "password").await?;
|
|
||||||
|
|
||||||
let mut stream1 = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s1 = TestScope::new(&mut stream1);
|
|
||||||
let mut stream2 = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s2 = TestScope::new(&mut stream2);
|
|
||||||
|
|
||||||
s1.send("PASS password").await?;
|
|
||||||
s1.send("NICK tester1").await?;
|
|
||||||
s1.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s1.expect_server_introduction("tester1").await?;
|
|
||||||
s1.expect_nothing().await?;
|
|
||||||
|
|
||||||
s2.send("PASS password").await?;
|
|
||||||
s2.send("NICK tester2").await?;
|
|
||||||
s2.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s2.expect_server_introduction("tester2").await?;
|
|
||||||
s2.expect_nothing().await?;
|
|
||||||
|
|
||||||
// Join the channel from the first user
|
|
||||||
s1.send("JOIN #test").await?;
|
|
||||||
s1.expect(":tester1 JOIN #test").await?;
|
|
||||||
s1.expect(":testserver 332 tester1 #test :New room").await?;
|
|
||||||
s1.expect(":testserver 353 tester1 = #test :tester1").await?;
|
|
||||||
s1.expect(":testserver 366 tester1 #test :End of /NAMES list").await?;
|
|
||||||
// Then join the channel from the second user
|
|
||||||
s2.send("JOIN #test").await?;
|
|
||||||
s2.expect(":tester2 JOIN #test").await?;
|
|
||||||
s2.expect(":testserver 332 tester2 #test :New room").await?;
|
|
||||||
s2.expect_that(|msg| {
|
|
||||||
msg == ":testserver 353 tester2 = #test :tester1 tester2"
|
|
||||||
|| msg == ":testserver 353 tester2 = #test :tester2 tester1"
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
s2.expect(":testserver 366 tester2 #test :End of /NAMES list").await?;
|
|
||||||
// The first user should receive the JOIN message from the second user
|
|
||||||
s1.expect(":tester2 JOIN #test").await?;
|
|
||||||
s1.expect_nothing().await?;
|
|
||||||
s2.expect_nothing().await?;
|
|
||||||
// Send a message from the second user
|
|
||||||
s2.send("PRIVMSG #test :Hello").await?;
|
|
||||||
// The first user should receive the message
|
|
||||||
s1.expect(":tester2 PRIVMSG #test :Hello").await?;
|
|
||||||
// Leave the channel from the first user
|
|
||||||
s1.send("PART #test").await?;
|
|
||||||
s1.expect(":tester1 PART #test").await?;
|
|
||||||
// The second user should receive the PART message
|
|
||||||
s2.expect(":tester1 PART #test").await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
IRC SASL doc: https://ircv3.net/specs/extensions/sasl-3.1.html
|
|
||||||
AUTHENTICATE doc: https://modern.ircdocs.horse/#authenticate-message
|
|
||||||
*/
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_cap_full_negotiation() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
|
||||||
server.storage.set_password("tester", "password").await?;
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
|
|
||||||
s.send("CAP LS 302").await?;
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.expect(":testserver CAP * LS :sasl=PLAIN").await?;
|
|
||||||
s.send("CAP REQ :sasl").await?;
|
|
||||||
s.expect(":testserver CAP tester ACK :sasl").await?;
|
|
||||||
s.send("AUTHENTICATE PLAIN").await?;
|
|
||||||
s.expect(":testserver AUTHENTICATE +").await?;
|
|
||||||
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
|
||||||
s.expect(":testserver 900 tester tester tester :You are now logged in as tester").await?;
|
|
||||||
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
|
||||||
|
|
||||||
s.expect_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]
|
|
||||||
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]
|
|
||||||
async fn scenario_cap_short_negotiation() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
|
||||||
server.storage.set_password("tester", "password").await?;
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
s.send("CAP REQ :sasl").await?;
|
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.expect(":testserver CAP tester ACK :sasl").await?;
|
|
||||||
s.send("AUTHENTICATE PLAIN").await?;
|
|
||||||
s.expect(":testserver AUTHENTICATE +").await?;
|
|
||||||
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
|
||||||
s.expect(":testserver 900 tester tester tester :You are now logged in as tester").await?;
|
|
||||||
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
|
||||||
|
|
||||||
s.expect_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]
|
|
||||||
async fn scenario_cap_sasl_fail() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
|
||||||
server.storage.set_password("tester", "password").await?;
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
|
|
||||||
s.send("CAP LS 302").await?;
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.expect(":testserver CAP * LS :sasl=PLAIN").await?;
|
|
||||||
s.send("CAP REQ :sasl").await?;
|
|
||||||
s.expect(":testserver CAP tester ACK :sasl").await?;
|
|
||||||
s.send("AUTHENTICATE SHA256").await?;
|
|
||||||
s.expect(":testserver 904 tester :Unsupported mechanism").await?;
|
|
||||||
s.send("AUTHENTICATE PLAIN").await?;
|
|
||||||
s.expect(":testserver AUTHENTICATE +").await?;
|
|
||||||
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZDE=").await?;
|
|
||||||
s.expect(":testserver 904 tester :Bad credentials").await?;
|
|
||||||
s.send("AUTHENTICATE dGVzdGVyAHRlc3RlcgBwYXNzd29yZA==").await?; // base64-encoded 'tester\x00tester\x00password'
|
|
||||||
s.expect(":testserver 900 tester tester tester :You are now logged in as tester").await?;
|
|
||||||
s.expect(":testserver 903 tester :SASL authentication successful").await?;
|
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
|
||||||
|
|
||||||
s.expect_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]
|
|
||||||
async fn terminate_socket_scenario() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
server.storage.create_user("tester").await?;
|
|
||||||
server.storage.set_password("tester", "password").await?;
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
|
|
||||||
s.send("NICK tester").await?;
|
|
||||||
s.send("CAP REQ :sasl").await?;
|
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
|
||||||
s.expect(":testserver CAP tester ACK :sasl").await?;
|
|
||||||
s.send("AUTHENTICATE PLAIN").await?;
|
|
||||||
s.expect(":testserver AUTHENTICATE +").await?;
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
assert_eq!(stream.read_u8().await.unwrap_err().kind(), ErrorKind::UnexpectedEof);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
|
@ -13,13 +13,8 @@ prometheus.workspace = true
|
||||||
futures-util.workspace = true
|
futures-util.workspace = true
|
||||||
|
|
||||||
quick-xml.workspace = true
|
quick-xml.workspace = true
|
||||||
sasl.workspace = true
|
|
||||||
proto-xmpp = { path = "../proto-xmpp" }
|
proto-xmpp = { path = "../proto-xmpp" }
|
||||||
uuid = { version = "1.3.0", features = ["v4"] }
|
uuid = { version = "1.3.0", features = ["v4"] }
|
||||||
tokio-rustls = { version = "0.24.1", features = ["dangerous_configuration"] }
|
tokio-rustls = "0.24.1"
|
||||||
rustls-pemfile = "1.0.2"
|
rustls-pemfile = "1.0.2"
|
||||||
derive_more.workspace = true
|
derive_more.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
tracing-subscriber.workspace = true
|
|
||||||
assert_matches = "1.5.0"
|
|
||||||
|
|
|
@ -1,223 +0,0 @@
|
||||||
//! Handling of all client2server iq stanzas
|
|
||||||
|
|
||||||
use quick_xml::events::Event;
|
|
||||||
|
|
||||||
use lavina_core::room::{RoomId, RoomRegistry};
|
|
||||||
use proto_xmpp::bind::{BindResponse, Jid, Name, Server};
|
|
||||||
use proto_xmpp::client::{Iq, IqError, IqErrorType, IqType};
|
|
||||||
use proto_xmpp::disco::{Feature, Identity, InfoQuery, Item, ItemQuery};
|
|
||||||
use proto_xmpp::roster::RosterQuery;
|
|
||||||
use proto_xmpp::session::Session;
|
|
||||||
|
|
||||||
use crate::proto::IqClientBody;
|
|
||||||
use crate::XmppConnection;
|
|
||||||
|
|
||||||
use proto_xmpp::xml::ToXml;
|
|
||||||
|
|
||||||
impl<'a> XmppConnection<'a> {
|
|
||||||
pub async fn handle_iq(&self, output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>) {
|
|
||||||
match iq.body {
|
|
||||||
IqClientBody::Bind(_) => {
|
|
||||||
let req = Iq {
|
|
||||||
from: None,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Result,
|
|
||||||
body: BindResponse(Jid {
|
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
|
||||||
server: Server(self.hostname.clone()),
|
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
req.serialize(output);
|
|
||||||
}
|
|
||||||
IqClientBody::Session(_) => {
|
|
||||||
let req = Iq {
|
|
||||||
from: None,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Result,
|
|
||||||
body: Session,
|
|
||||||
};
|
|
||||||
req.serialize(output);
|
|
||||||
}
|
|
||||||
IqClientBody::Roster(_) => {
|
|
||||||
let req = Iq {
|
|
||||||
from: None,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Result,
|
|
||||||
body: RosterQuery,
|
|
||||||
};
|
|
||||||
req.serialize(output);
|
|
||||||
}
|
|
||||||
IqClientBody::DiscoInfo(info) => {
|
|
||||||
let response = self.disco_info(iq.to.as_ref(), &info).await;
|
|
||||||
match response {
|
|
||||||
Ok(response) => {
|
|
||||||
let req = Iq {
|
|
||||||
from: iq.to,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Result,
|
|
||||||
body: response,
|
|
||||||
};
|
|
||||||
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) => {
|
|
||||||
let response = self.disco_items(iq.to.as_ref(), &item, self.rooms).await;
|
|
||||||
let req = Iq {
|
|
||||||
from: iq.to,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Result,
|
|
||||||
body: response,
|
|
||||||
};
|
|
||||||
req.serialize(output);
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
let req = Iq {
|
|
||||||
from: None,
|
|
||||||
id: iq.id,
|
|
||||||
to: None,
|
|
||||||
r#type: IqType::Error,
|
|
||||||
body: IqError {
|
|
||||||
r#type: IqErrorType::Cancel,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
req.serialize(output);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn disco_info(&self, to: Option<&Jid>, req: &InfoQuery) -> Result<InfoQuery, IqError> {
|
|
||||||
let identity;
|
|
||||||
let feature;
|
|
||||||
|
|
||||||
match to {
|
|
||||||
Some(Jid {
|
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname => {
|
|
||||||
identity = vec![Identity {
|
|
||||||
category: "server".into(),
|
|
||||||
name: None,
|
|
||||||
r#type: "im".into(),
|
|
||||||
}];
|
|
||||||
feature = vec![
|
|
||||||
Feature::new("http://jabber.org/protocol/disco#info"),
|
|
||||||
Feature::new("http://jabber.org/protocol/disco#items"),
|
|
||||||
Feature::new("iq"),
|
|
||||||
Feature::new("presence"),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
Some(Jid {
|
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname_rooms => {
|
|
||||||
identity = vec![Identity {
|
|
||||||
category: "conference".into(),
|
|
||||||
name: Some("Chat rooms".into()),
|
|
||||||
r#type: "text".into(),
|
|
||||||
}];
|
|
||||||
feature = vec![
|
|
||||||
Feature::new("http://jabber.org/protocol/disco#info"),
|
|
||||||
Feature::new("http://jabber.org/protocol/disco#items"),
|
|
||||||
Feature::new("http://jabber.org/protocol/muc"),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
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![];
|
|
||||||
feature = vec![];
|
|
||||||
}
|
|
||||||
};
|
|
||||||
Ok(InfoQuery {
|
|
||||||
node: None,
|
|
||||||
identity,
|
|
||||||
feature,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn disco_items(&self, to: Option<&Jid>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
|
|
||||||
let item = match to {
|
|
||||||
Some(Jid {
|
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname => {
|
|
||||||
vec![Item {
|
|
||||||
jid: Jid {
|
|
||||||
name: None,
|
|
||||||
server: Server(self.hostname_rooms.clone()),
|
|
||||||
resource: None,
|
|
||||||
},
|
|
||||||
name: None,
|
|
||||||
node: None,
|
|
||||||
}]
|
|
||||||
}
|
|
||||||
Some(Jid {
|
|
||||||
name: None,
|
|
||||||
server,
|
|
||||||
resource: None,
|
|
||||||
}) if server.0 == self.hostname_rooms => {
|
|
||||||
let room_list = rooms.get_all_rooms().await;
|
|
||||||
room_list
|
|
||||||
.into_iter()
|
|
||||||
.map(|room_info| Item {
|
|
||||||
jid: Jid {
|
|
||||||
name: Some(Name(room_info.id.into_inner())),
|
|
||||||
server: Server(self.hostname_rooms.clone()),
|
|
||||||
resource: None,
|
|
||||||
},
|
|
||||||
name: None,
|
|
||||||
node: None,
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
_ => vec![],
|
|
||||||
};
|
|
||||||
ItemQuery { item }
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,4 +1,4 @@
|
||||||
#![feature(coroutines, coroutine_trait, type_alias_impl_trait, impl_trait_in_assoc_type)]
|
#![feature(generators, generator_trait, type_alias_impl_trait, impl_trait_in_assoc_type)]
|
||||||
|
|
||||||
mod proto;
|
mod proto;
|
||||||
|
|
||||||
|
@ -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};
|
||||||
|
@ -23,28 +24,23 @@ use tokio_rustls::TlsAcceptor;
|
||||||
|
|
||||||
use lavina_core::player::{PlayerConnection, PlayerId, PlayerRegistry};
|
use lavina_core::player::{PlayerConnection, PlayerId, PlayerRegistry};
|
||||||
use lavina_core::prelude::*;
|
use lavina_core::prelude::*;
|
||||||
use lavina_core::repo::Storage;
|
use lavina_core::room::{RoomId, RoomRegistry};
|
||||||
use lavina_core::room::RoomRegistry;
|
|
||||||
use lavina_core::terminator::Terminator;
|
use lavina_core::terminator::Terminator;
|
||||||
use lavina_core::LavinaCore;
|
use proto_xmpp::bind::{BindResponse, Jid, Name, Resource, Server};
|
||||||
use proto_xmpp::bind::{Name, Resource};
|
use proto_xmpp::client::{Iq, Message, MessageType, Presence};
|
||||||
|
use proto_xmpp::disco::*;
|
||||||
|
use proto_xmpp::roster::RosterQuery;
|
||||||
|
use proto_xmpp::session::Session;
|
||||||
use proto_xmpp::stream::*;
|
use proto_xmpp::stream::*;
|
||||||
use proto_xmpp::xml::{Continuation, FromXml, Parser, ToXml};
|
use proto_xmpp::xml::{Continuation, FromXml, Parser, ToXml};
|
||||||
use sasl::AuthBody;
|
|
||||||
|
|
||||||
use self::proto::ClientPacket;
|
use self::proto::{ClientPacket, IqClientBody};
|
||||||
|
|
||||||
mod iq;
|
|
||||||
mod message;
|
|
||||||
mod presence;
|
|
||||||
mod updates;
|
|
||||||
|
|
||||||
#[derive(Deserialize, Debug, Clone)]
|
#[derive(Deserialize, Debug, Clone)]
|
||||||
pub struct ServerConfig {
|
pub struct ServerConfig {
|
||||||
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 {
|
||||||
|
@ -53,37 +49,18 @@ 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,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct RunningServer {
|
|
||||||
pub addr: SocketAddr,
|
|
||||||
terminator: Terminator,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RunningServer {
|
|
||||||
pub async fn terminate(self) -> Result<()> {
|
|
||||||
self.terminator.terminate().await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn launch(
|
pub async fn launch(
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
core: LavinaCore,
|
players: PlayerRegistry,
|
||||||
|
rooms: RoomRegistry,
|
||||||
metrics: MetricsRegistry,
|
metrics: MetricsRegistry,
|
||||||
storage: Storage,
|
) -> Result<Terminator> {
|
||||||
) -> Result<RunningServer> {
|
|
||||||
log::info!("Starting XMPP projection");
|
log::info!("Starting XMPP projection");
|
||||||
|
|
||||||
let certs = certs(&mut SyncBufReader::new(File::open(config.cert)?))?;
|
let certs = certs(&mut SyncBufReader::new(File::open(config.cert)?))?;
|
||||||
|
@ -91,7 +68,7 @@ pub async fn launch(
|
||||||
|
|
||||||
let key = match read_one(&mut SyncBufReader::new(File::open(config.key)?))? {
|
let key = match read_one(&mut SyncBufReader::new(File::open(config.key)?))? {
|
||||||
Some(PemItem::ECKey(k) | PemItem::PKCS8Key(k) | PemItem::RSAKey(k)) => PrivateKey(k),
|
Some(PemItem::ECKey(k) | PemItem::PKCS8Key(k) | PemItem::RSAKey(k)) => PrivateKey(k),
|
||||||
_ => return Err(fail("no keys in file")),
|
_ => panic!("no keys in file"),
|
||||||
};
|
};
|
||||||
|
|
||||||
let loaded_config = Arc::new(LoadedConfig {
|
let loaded_config = Arc::new(LoadedConfig {
|
||||||
|
@ -100,8 +77,6 @@ pub async fn launch(
|
||||||
});
|
});
|
||||||
|
|
||||||
let listener = TcpListener::bind(config.listen_on).await?;
|
let listener = TcpListener::bind(config.listen_on).await?;
|
||||||
let addr = listener.local_addr()?;
|
|
||||||
|
|
||||||
let terminator = Terminator::spawn(|mut termination| async move {
|
let terminator = Terminator::spawn(|mut termination| async move {
|
||||||
let (stopped_tx, mut stopped_rx) = channel(32);
|
let (stopped_tx, mut stopped_rx) = channel(32);
|
||||||
let mut actors = HashMap::new();
|
let mut actors = HashMap::new();
|
||||||
|
@ -122,14 +97,13 @@ pub async fn launch(
|
||||||
// TODO kill the older connection and restart it
|
// TODO kill the older connection and restart it
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let core = core.clone();
|
let players = players.clone();
|
||||||
let storage = storage.clone();
|
let rooms = rooms.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, core, storage, hostname, termination).await {
|
match handle_socket(loaded_config, stream, &socket_addr, players, rooms, 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}"),
|
||||||
}
|
}
|
||||||
|
@ -160,16 +134,15 @@ pub async fn launch(
|
||||||
Ok(())
|
Ok(())
|
||||||
});
|
});
|
||||||
log::info!("Started XMPP projection");
|
log::info!("Started XMPP projection");
|
||||||
Ok(RunningServer { addr, terminator })
|
Ok(terminator)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_socket(
|
async fn handle_socket(
|
||||||
cert_config: Arc<LoadedConfig>,
|
config: Arc<LoadedConfig>,
|
||||||
mut stream: TcpStream,
|
mut stream: TcpStream,
|
||||||
socket_addr: &SocketAddr,
|
socket_addr: &SocketAddr,
|
||||||
mut core: LavinaCore,
|
mut players: PlayerRegistry,
|
||||||
mut storage: Storage,
|
rooms: RoomRegistry,
|
||||||
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}");
|
||||||
|
@ -178,54 +151,37 @@ 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...");
|
|
||||||
let acceptor = TlsAcceptor::from(Arc::new(config));
|
let acceptor = TlsAcceptor::from(Arc::new(config));
|
||||||
let new_stream = acceptor.accept(stream).await?;
|
let new_stream = acceptor.accept(stream).await?;
|
||||||
log::debug!("TLS connection established");
|
log::debug!("TLS connection established");
|
||||||
|
|
||||||
let (a, b) = tokio::io::split(new_stream);
|
let (a, b) = tokio::io::split(new_stream);
|
||||||
let mut xml_reader = NsReader::from_reader(BufReader::new(a));
|
let mut xml_reader = NsReader::from_reader(BufReader::new(a));
|
||||||
let mut xml_writer = Writer::new(BufWriter::new(b));
|
let mut xml_writer = Writer::new(b);
|
||||||
|
|
||||||
pin!(termination);
|
let authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf).await?;
|
||||||
select! {
|
log::debug!("User authenticated");
|
||||||
biased;
|
let mut connection = players.connect_to_player(authenticated.player_id.clone()).await;
|
||||||
_ = &mut termination =>{
|
socket_final(
|
||||||
log::info!("Socket handling was terminated");
|
&mut xml_reader,
|
||||||
return Ok(())
|
&mut xml_writer,
|
||||||
},
|
&mut reader_buf,
|
||||||
authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf, &mut storage, &hostname) => {
|
&authenticated,
|
||||||
match authenticated {
|
&mut connection,
|
||||||
Ok(authenticated) => {
|
&rooms,
|
||||||
let mut connection = core.players.connect_to_player(&authenticated.player_id).await;
|
)
|
||||||
socket_final(
|
.await?;
|
||||||
&mut xml_reader,
|
|
||||||
&mut xml_writer,
|
|
||||||
&mut reader_buf,
|
|
||||||
&authenticated,
|
|
||||||
&mut connection,
|
|
||||||
&core.rooms,
|
|
||||||
&hostname,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
},
|
|
||||||
Err(err) => {
|
|
||||||
log::error!("Authentication error: {:?}", err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
let a = xml_reader.into_inner().into_inner();
|
let a = xml_reader.into_inner().into_inner();
|
||||||
let b = xml_writer.into_inner().into_inner();
|
let b = xml_writer.into_inner();
|
||||||
a.unsplit(b).shutdown().await?;
|
a.unsplit(b).shutdown().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -234,18 +190,17 @@ 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
|
read_xml_header(xml_reader, reader_buf).await?;
|
||||||
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(),
|
||||||
|
@ -269,15 +224,15 @@ async fn socket_auth(
|
||||||
xml_reader: &mut NsReader<(impl AsyncBufRead + Unpin)>,
|
xml_reader: &mut NsReader<(impl AsyncBufRead + Unpin)>,
|
||||||
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,
|
|
||||||
hostname: &Str,
|
|
||||||
) -> Result<Authenticated> {
|
) -> Result<Authenticated> {
|
||||||
// TODO validate the server hostname received in the stream start
|
read_xml_header(xml_reader, reader_buf).await?;
|
||||||
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
||||||
|
|
||||||
xml_writer.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None))).await?;
|
xml_writer
|
||||||
|
.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None)))
|
||||||
|
.await?;
|
||||||
ServerStreamStart {
|
ServerStreamStart {
|
||||||
from: 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(),
|
||||||
|
@ -293,44 +248,16 @@ async fn socket_auth(
|
||||||
.await?;
|
.await?;
|
||||||
xml_writer.get_mut().flush().await?;
|
xml_writer.get_mut().flush().await?;
|
||||||
|
|
||||||
let auth: proto_xmpp::sasl::Auth = proto_xmpp::sasl::Auth::parse(xml_reader, reader_buf).await?;
|
let _ = proto_xmpp::sasl::Auth::parse(xml_reader, reader_buf).await?;
|
||||||
proto_xmpp::sasl::Success.write_xml(xml_writer).await?;
|
proto_xmpp::sasl::Success.write_xml(xml_writer).await?;
|
||||||
xml_writer.get_mut().flush().await?;
|
|
||||||
|
|
||||||
match AuthBody::from_str(&auth.body) {
|
let name: Str = "darova".into();
|
||||||
Ok(logopass) => {
|
Ok(Authenticated {
|
||||||
let name = &logopass.login;
|
player_id: PlayerId::from("darova")?,
|
||||||
let stored_user = storage.retrieve_user_by_name(name).await?;
|
xmpp_name: Name(name.clone()),
|
||||||
|
xmpp_resource: Resource(name.clone()),
|
||||||
let stored_user = match stored_user {
|
xmpp_muc_name: Resource(name),
|
||||||
Some(u) => u,
|
})
|
||||||
None => {
|
|
||||||
log::info!("User '{}' not found", name);
|
|
||||||
return Err(fail("no user found"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// TODO return proper XML errors to the client
|
|
||||||
|
|
||||||
if stored_user.password.is_none() {
|
|
||||||
log::info!("Password not defined for user '{}'", name);
|
|
||||||
return Err(fail("password is not defined"));
|
|
||||||
}
|
|
||||||
if stored_user.password.as_deref() != Some(&logopass.password) {
|
|
||||||
log::info!("Incorrect password supplied for user '{}'", name);
|
|
||||||
return Err(fail("passwords do not match"));
|
|
||||||
}
|
|
||||||
|
|
||||||
let name: Str = name.as_str().into();
|
|
||||||
|
|
||||||
Ok(Authenticated {
|
|
||||||
player_id: PlayerId::from(name.clone())?,
|
|
||||||
xmpp_name: Name(name.clone()),
|
|
||||||
xmpp_resource: Resource(name.clone()),
|
|
||||||
xmpp_muc_name: Resource(name.clone()),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Err(e) => return Err(e),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn socket_final(
|
async fn socket_final(
|
||||||
|
@ -340,14 +267,15 @@ 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
|
read_xml_header(xml_reader, reader_buf).await?;
|
||||||
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
let _ = ClientStreamStart::parse(xml_reader, reader_buf).await?;
|
||||||
|
|
||||||
xml_writer.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None))).await?;
|
xml_writer
|
||||||
|
.write_event_async(Event::Decl(BytesDecl::new("1.0", None, None)))
|
||||||
|
.await?;
|
||||||
ServerStreamStart {
|
ServerStreamStart {
|
||||||
from: 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(),
|
||||||
|
@ -369,26 +297,19 @@ async fn socket_final(
|
||||||
let mut next_xml_event = Box::pin(xml_reader.read_resolved_event_into_async(reader_buf));
|
let mut next_xml_event = Box::pin(xml_reader.read_resolved_event_into_async(reader_buf));
|
||||||
|
|
||||||
'outer: loop {
|
'outer: loop {
|
||||||
let mut conn = XmppConnection {
|
|
||||||
user: authenticated,
|
|
||||||
user_handle,
|
|
||||||
rooms,
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
match parser.consume(ns, &event) {
|
match parser.consume(ns, &event) {
|
||||||
Continuation::Final(res) => {
|
Continuation::Final(res) => {
|
||||||
let res = res?;
|
let res = res?;
|
||||||
let stop = conn.handle_packet(&mut events, res).await?;
|
let stop = handle_packet(&mut events, res, authenticated, user_handle, rooms).await?;
|
||||||
for i in &events {
|
for i in &events {
|
||||||
xml_writer.write_event_async(i).await?;
|
xml_writer.write_event_async(i).await?;
|
||||||
}
|
}
|
||||||
|
@ -403,9 +324,32 @@ async fn socket_final(
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
},
|
},
|
||||||
update = conn.user_handle.receiver.recv() => {
|
update = user_handle.receiver.recv() => {
|
||||||
if let Some(update) = update {
|
if let Some(update) = update {
|
||||||
conn.handle_update(&mut events, update).await?;
|
match update {
|
||||||
|
lavina_core::player::Updates::NewMessage { room_id, author_id, body } => {
|
||||||
|
Message::<()> {
|
||||||
|
to: Some(Jid {
|
||||||
|
name: Some(authenticated.xmpp_name.clone()),
|
||||||
|
server: Server("localhost".into()),
|
||||||
|
resource: Some(authenticated.xmpp_resource.clone()),
|
||||||
|
}),
|
||||||
|
from: Some(Jid {
|
||||||
|
name: Some(Name(room_id.into_inner().into())),
|
||||||
|
server: Server("rooms.localhost".into()),
|
||||||
|
resource: Some(Resource(author_id.into_inner().into())),
|
||||||
|
}),
|
||||||
|
id: None,
|
||||||
|
r#type: proto_xmpp::client::MessageType::Groupchat,
|
||||||
|
lang: None,
|
||||||
|
subject: None,
|
||||||
|
body: body.into(),
|
||||||
|
custom: vec![],
|
||||||
|
}
|
||||||
|
.serialize(&mut events);
|
||||||
|
}
|
||||||
|
_ => {},
|
||||||
|
}
|
||||||
for i in &events {
|
for i in &events {
|
||||||
xml_writer.write_event_async(i).await?;
|
xml_writer.write_event_async(i).await?;
|
||||||
}
|
}
|
||||||
|
@ -427,34 +371,267 @@ async fn socket_final(
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
struct XmppConnection<'a> {
|
async fn handle_packet(
|
||||||
user: &'a Authenticated,
|
output: &mut Vec<Event<'static>>,
|
||||||
user_handle: &'a mut PlayerConnection,
|
packet: ClientPacket,
|
||||||
rooms: &'a RoomRegistry,
|
user: &Authenticated,
|
||||||
hostname: Str,
|
user_handle: &mut PlayerConnection,
|
||||||
hostname_rooms: Str,
|
rooms: &RoomRegistry,
|
||||||
|
) -> Result<bool> {
|
||||||
|
Ok(match packet {
|
||||||
|
proto::ClientPacket::Iq(iq) => {
|
||||||
|
handle_iq(output, iq, rooms).await;
|
||||||
|
false
|
||||||
|
}
|
||||||
|
proto::ClientPacket::Message(m) => {
|
||||||
|
if let Some(Jid {
|
||||||
|
name: Some(name),
|
||||||
|
server,
|
||||||
|
resource: _,
|
||||||
|
}) = m.to
|
||||||
|
{
|
||||||
|
if server.0.as_ref() == "rooms.localhost" && m.r#type == MessageType::Groupchat {
|
||||||
|
user_handle
|
||||||
|
.send_message(RoomId::from(name.0.clone())?, m.body.clone().into())
|
||||||
|
.await?;
|
||||||
|
Message::<()> {
|
||||||
|
to: Some(Jid {
|
||||||
|
name: Some(user.xmpp_name.clone()),
|
||||||
|
server: Server("localhost".into()),
|
||||||
|
resource: Some(user.xmpp_resource.clone()),
|
||||||
|
}),
|
||||||
|
from: Some(Jid {
|
||||||
|
name: Some(name),
|
||||||
|
server: Server("rooms.localhost".into()),
|
||||||
|
resource: Some(user.xmpp_muc_name.clone()),
|
||||||
|
}),
|
||||||
|
id: m.id,
|
||||||
|
r#type: proto_xmpp::client::MessageType::Groupchat,
|
||||||
|
lang: None,
|
||||||
|
subject: None,
|
||||||
|
body: m.body.clone(),
|
||||||
|
custom: vec![],
|
||||||
|
}
|
||||||
|
.serialize(output);
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
todo!()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
proto::ClientPacket::Presence(p) => {
|
||||||
|
let response = if p.to.is_none() {
|
||||||
|
Presence::<()> {
|
||||||
|
to: Some(Jid {
|
||||||
|
name: Some(user.xmpp_name.clone()),
|
||||||
|
server: Server("localhost".into()),
|
||||||
|
resource: Some(user.xmpp_resource.clone()),
|
||||||
|
}),
|
||||||
|
from: Some(Jid {
|
||||||
|
name: Some(user.xmpp_name.clone()),
|
||||||
|
server: Server("localhost".into()),
|
||||||
|
resource: Some(user.xmpp_resource.clone()),
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
} else if let Some(Jid {
|
||||||
|
name: Some(name),
|
||||||
|
server,
|
||||||
|
resource: Some(resource),
|
||||||
|
}) = p.to
|
||||||
|
{
|
||||||
|
let a = user_handle.join_room(RoomId::from(name.0.clone())?).await?;
|
||||||
|
Presence::<()> {
|
||||||
|
to: Some(Jid {
|
||||||
|
name: Some(user.xmpp_name.clone()),
|
||||||
|
server: Server("localhost".into()),
|
||||||
|
resource: Some(user.xmpp_resource.clone()),
|
||||||
|
}),
|
||||||
|
from: Some(Jid {
|
||||||
|
name: Some(name.clone()),
|
||||||
|
server: Server("rooms.localhost".into()),
|
||||||
|
resource: Some(user.xmpp_muc_name.clone()),
|
||||||
|
}),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Presence::<()>::default()
|
||||||
|
};
|
||||||
|
response.serialize(output);
|
||||||
|
false
|
||||||
|
}
|
||||||
|
proto::ClientPacket::StreamEnd => {
|
||||||
|
ServerStreamEnd.serialize(output);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> XmppConnection<'a> {
|
async fn handle_iq(output: &mut Vec<Event<'static>>, iq: Iq<IqClientBody>, rooms: &RoomRegistry) {
|
||||||
async fn handle_packet(&mut self, output: &mut Vec<Event<'static>>, packet: ClientPacket) -> Result<bool> {
|
match iq.body {
|
||||||
let res = match packet {
|
proto::IqClientBody::Bind(b) => {
|
||||||
ClientPacket::Iq(iq) => {
|
let req = Iq {
|
||||||
self.handle_iq(output, iq).await;
|
from: None,
|
||||||
false
|
id: iq.id,
|
||||||
}
|
to: None,
|
||||||
ClientPacket::Message(m) => {
|
r#type: proto_xmpp::client::IqType::Result,
|
||||||
self.handle_message(output, m).await?;
|
body: BindResponse(Jid {
|
||||||
false
|
name: Some(Name("darova".into())),
|
||||||
}
|
server: Server("localhost".into()),
|
||||||
ClientPacket::Presence(p) => {
|
resource: Some(Resource("kek".into())),
|
||||||
self.handle_presence(output, p).await?;
|
}),
|
||||||
false
|
};
|
||||||
}
|
req.serialize(output);
|
||||||
ClientPacket::StreamEnd => {
|
}
|
||||||
ServerStreamEnd.serialize(output);
|
proto::IqClientBody::Session(_) => {
|
||||||
true
|
let req = Iq {
|
||||||
}
|
from: None,
|
||||||
};
|
id: iq.id,
|
||||||
Ok(res)
|
to: None,
|
||||||
|
r#type: proto_xmpp::client::IqType::Result,
|
||||||
|
body: Session,
|
||||||
|
};
|
||||||
|
req.serialize(output);
|
||||||
|
}
|
||||||
|
proto::IqClientBody::Roster(_) => {
|
||||||
|
let req = Iq {
|
||||||
|
from: None,
|
||||||
|
id: iq.id,
|
||||||
|
to: None,
|
||||||
|
r#type: proto_xmpp::client::IqType::Result,
|
||||||
|
body: RosterQuery,
|
||||||
|
};
|
||||||
|
req.serialize(output);
|
||||||
|
}
|
||||||
|
proto::IqClientBody::DiscoInfo(info) => {
|
||||||
|
let response = disco_info(iq.to.as_deref(), &info);
|
||||||
|
let req = Iq {
|
||||||
|
from: iq.to,
|
||||||
|
id: iq.id,
|
||||||
|
to: None,
|
||||||
|
r#type: proto_xmpp::client::IqType::Result,
|
||||||
|
body: response,
|
||||||
|
};
|
||||||
|
req.serialize(output);
|
||||||
|
}
|
||||||
|
proto::IqClientBody::DiscoItem(item) => {
|
||||||
|
let response = disco_items(iq.to.as_deref(), &item, rooms).await;
|
||||||
|
let req = Iq {
|
||||||
|
from: iq.to,
|
||||||
|
id: iq.id,
|
||||||
|
to: None,
|
||||||
|
r#type: proto_xmpp::client::IqType::Result,
|
||||||
|
body: response,
|
||||||
|
};
|
||||||
|
req.serialize(output);
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let req = Iq {
|
||||||
|
from: None,
|
||||||
|
id: iq.id,
|
||||||
|
to: None,
|
||||||
|
r#type: proto_xmpp::client::IqType::Error,
|
||||||
|
body: (),
|
||||||
|
};
|
||||||
|
req.serialize(output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn disco_info(to: Option<&str>, req: &InfoQuery) -> InfoQuery {
|
||||||
|
let identity;
|
||||||
|
let feature;
|
||||||
|
match to {
|
||||||
|
Some("localhost") => {
|
||||||
|
identity = vec![Identity {
|
||||||
|
category: "server".into(),
|
||||||
|
name: None,
|
||||||
|
r#type: "im".into(),
|
||||||
|
}];
|
||||||
|
feature = vec![
|
||||||
|
Feature::new("http://jabber.org/protocol/disco#info"),
|
||||||
|
Feature::new("http://jabber.org/protocol/disco#items"),
|
||||||
|
Feature::new("iq"),
|
||||||
|
Feature::new("presence"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
Some("rooms.localhost") => {
|
||||||
|
identity = vec![Identity {
|
||||||
|
category: "conference".into(),
|
||||||
|
name: Some("Chat rooms".into()),
|
||||||
|
r#type: "text".into(),
|
||||||
|
}];
|
||||||
|
feature = vec![
|
||||||
|
Feature::new("http://jabber.org/protocol/disco#info"),
|
||||||
|
Feature::new("http://jabber.org/protocol/disco#items"),
|
||||||
|
Feature::new("http://jabber.org/protocol/muc"),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
identity = vec![];
|
||||||
|
feature = vec![];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
InfoQuery {
|
||||||
|
node: None,
|
||||||
|
identity,
|
||||||
|
feature,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn disco_items(to: Option<&str>, req: &ItemQuery, rooms: &RoomRegistry) -> ItemQuery {
|
||||||
|
let item = match to {
|
||||||
|
Some("localhost") => {
|
||||||
|
vec![Item {
|
||||||
|
jid: Jid {
|
||||||
|
name: None,
|
||||||
|
server: Server("rooms.localhost".into()),
|
||||||
|
resource: None,
|
||||||
|
},
|
||||||
|
name: None,
|
||||||
|
node: None,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
Some("rooms.localhost") => {
|
||||||
|
let room_list = rooms.get_all_rooms().await;
|
||||||
|
room_list
|
||||||
|
.into_iter()
|
||||||
|
.map(|room_info| Item {
|
||||||
|
jid: Jid {
|
||||||
|
name: Some(Name(room_info.id.into_inner())),
|
||||||
|
server: Server("rooms.localhost".into()),
|
||||||
|
resource: None,
|
||||||
|
},
|
||||||
|
name: None,
|
||||||
|
node: None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
_ => vec![],
|
||||||
|
};
|
||||||
|
ItemQuery { item }
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_xml_header(
|
||||||
|
xml_reader: &mut NsReader<(impl AsyncBufRead + Unpin)>,
|
||||||
|
reader_buf: &mut Vec<u8>,
|
||||||
|
) -> Result<()> {
|
||||||
|
if let Event::Decl(bytes) = xml_reader.read_event_into_async(reader_buf).await? {
|
||||||
|
// this is <?xml ...> header
|
||||||
|
if let Some(encoding) = bytes.encoding() {
|
||||||
|
let encoding = encoding?;
|
||||||
|
if &*encoding == b"UTF-8" {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(anyhow!("Unsupported encoding: {encoding:?}"))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Err(fail("No XML encoding provided"))
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Err(anyhow!("Expected XML header"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,50 +0,0 @@
|
||||||
//! Handling of all client2server message stanzas
|
|
||||||
|
|
||||||
use quick_xml::events::Event;
|
|
||||||
|
|
||||||
use lavina_core::prelude::*;
|
|
||||||
use lavina_core::room::RoomId;
|
|
||||||
use proto_xmpp::bind::{Jid, Server};
|
|
||||||
use proto_xmpp::client::{Message, MessageType};
|
|
||||||
use proto_xmpp::xml::{Ignore, ToXml};
|
|
||||||
|
|
||||||
use crate::XmppConnection;
|
|
||||||
|
|
||||||
impl<'a> XmppConnection<'a> {
|
|
||||||
pub async fn handle_message(&mut self, output: &mut Vec<Event<'static>>, m: Message<Ignore>) -> Result<()> {
|
|
||||||
if let Some(Jid {
|
|
||||||
name: Some(name),
|
|
||||||
server,
|
|
||||||
resource: _,
|
|
||||||
}) = m.to
|
|
||||||
{
|
|
||||||
if server.0.as_ref() == &*self.hostname_rooms && m.r#type == MessageType::Groupchat {
|
|
||||||
self.user_handle.send_message(RoomId::from(name.0.clone())?, m.body.clone().into()).await?;
|
|
||||||
Message::<()> {
|
|
||||||
to: Some(Jid {
|
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
|
||||||
server: Server(self.hostname.clone()),
|
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
|
||||||
}),
|
|
||||||
from: Some(Jid {
|
|
||||||
name: Some(name),
|
|
||||||
server: Server(self.hostname_rooms.clone()),
|
|
||||||
resource: Some(self.user.xmpp_muc_name.clone()),
|
|
||||||
}),
|
|
||||||
id: m.id,
|
|
||||||
r#type: MessageType::Groupchat,
|
|
||||||
lang: None,
|
|
||||||
subject: None,
|
|
||||||
body: m.body.clone(),
|
|
||||||
custom: vec![],
|
|
||||||
}
|
|
||||||
.serialize(output);
|
|
||||||
Ok(())
|
|
||||||
} else {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
todo!()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,72 +0,0 @@
|
||||||
//! Handling of all client2server presence stanzas
|
|
||||||
|
|
||||||
use quick_xml::events::Event;
|
|
||||||
|
|
||||||
use lavina_core::prelude::*;
|
|
||||||
use lavina_core::room::RoomId;
|
|
||||||
use proto_xmpp::bind::{Jid, Name, Server};
|
|
||||||
use proto_xmpp::client::Presence;
|
|
||||||
use proto_xmpp::xml::{Ignore, ToXml};
|
|
||||||
|
|
||||||
use crate::XmppConnection;
|
|
||||||
|
|
||||||
impl<'a> XmppConnection<'a> {
|
|
||||||
pub async fn handle_presence(&mut self, output: &mut Vec<Event<'static>>, p: Presence<Ignore>) -> Result<()> {
|
|
||||||
match p.to {
|
|
||||||
None => {
|
|
||||||
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 {
|
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
|
||||||
server: Server(self.hostname.clone()),
|
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
|
||||||
}),
|
|
||||||
from: Some(Jid {
|
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
|
||||||
server: Server(self.hostname.clone()),
|
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
|
||||||
}),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
response.serialize(output);
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn muc_presence(&mut self, name: Name, output: &mut Vec<Event<'static>>) -> Result<()> {
|
|
||||||
let a = self.user_handle.join_room(RoomId::from(name.0.clone())?).await?;
|
|
||||||
// TODO handle bans
|
|
||||||
let response = Presence::<()> {
|
|
||||||
to: Some(Jid {
|
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
|
||||||
server: Server(self.hostname.clone()),
|
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
|
||||||
}),
|
|
||||||
from: Some(Jid {
|
|
||||||
name: Some(name.clone()),
|
|
||||||
server: Server(self.hostname_rooms.clone()),
|
|
||||||
resource: Some(self.user.xmpp_muc_name.clone()),
|
|
||||||
}),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
response.serialize(output);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,45 +0,0 @@
|
||||||
//! Handling of updates and converting them into server2client stanzas
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use quick_xml::events::Event;
|
|
||||||
|
|
||||||
use lavina_core::player::Updates;
|
|
||||||
use proto_xmpp::bind::{Jid, Name, Resource, Server};
|
|
||||||
use proto_xmpp::client::{Message, MessageType};
|
|
||||||
use proto_xmpp::xml::ToXml;
|
|
||||||
|
|
||||||
use crate::XmppConnection;
|
|
||||||
|
|
||||||
impl<'a> XmppConnection<'a> {
|
|
||||||
pub async fn handle_update(&mut self, output: &mut Vec<Event<'static>>, update: Updates) -> Result<()> {
|
|
||||||
match update {
|
|
||||||
Updates::NewMessage {
|
|
||||||
room_id,
|
|
||||||
author_id,
|
|
||||||
body,
|
|
||||||
} => {
|
|
||||||
Message::<()> {
|
|
||||||
to: Some(Jid {
|
|
||||||
name: Some(self.user.xmpp_name.clone()),
|
|
||||||
server: Server(self.hostname.clone()),
|
|
||||||
resource: Some(self.user.xmpp_resource.clone()),
|
|
||||||
}),
|
|
||||||
from: Some(Jid {
|
|
||||||
name: Some(Name(room_id.into_inner().into())),
|
|
||||||
server: Server(self.hostname_rooms.clone()),
|
|
||||||
resource: Some(Resource(author_id.into_inner().into())),
|
|
||||||
}),
|
|
||||||
id: None,
|
|
||||||
r#type: MessageType::Groupchat,
|
|
||||||
lang: None,
|
|
||||||
subject: None,
|
|
||||||
body: body.into(),
|
|
||||||
custom: vec![],
|
|
||||||
}
|
|
||||||
.serialize(output);
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,52 +0,0 @@
|
||||||
-----BEGIN PRIVATE KEY-----
|
|
||||||
MIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCuViBTGN8tMaQ8
|
|
||||||
G8zixL7duElTFCuP6wQhmDsX8ut4V3eEshUpDIIFkCSX17hzfI7duBp1pe7Ket+F
|
|
||||||
z5XjbV+ruvxpawvsCgsfGrwXE1vaDVJduy0JyRzLvRSXELWgAbcdllbvBKvGLtY1
|
|
||||||
ogm5YJWLbtgQJjutMoLisxn7Xd04fzMQy4aqhy2ZrsxyQSMINuR1Qz/VBzDZi4EH
|
|
||||||
Q08rb7GManQfbabbTs1I/GHuAM7PDeb/ou9AZHPASg2fzam5SJhvDYutHmX8wOS3
|
|
||||||
b+I+amI6g3N8fJssjx0ryAEL+c+Mbv6mXQhGqh7T++kXtB8h5GoLCOg3yGtaW7o0
|
|
||||||
PacAP1UsadDsGN13cWAAsytg1BxqgWk6IqA3Yff5uc2A+TYmX5K5DV46sonovybo
|
|
||||||
FI9fdKmL4oCbMIz+Tq+L5vHsdUh5/5S6F2RIKQDJIDYJfE7XVCPyToabQirQsQ/B
|
|
||||||
n27L0bCO1hD9cGR+z5td9TPGxrm7GUVGZ/fC58Q4WD/TrVhC3pUq8n7hMzGakg+w
|
|
||||||
Ri7FSJTPIZQXiTL/HtPleW+1y6d8Q84UI6Qm39vVueS5YSCjFCiQW2feod+L4sTU
|
|
||||||
sE0Rumbvb+saS6cmX7ZBzdgJhP9J5FiAOPqswgCS5w54F5hvfbg+yS4SgeKrvZF3
|
|
||||||
dAf+3wW8r039sFN+R/gQowxZcYZwOwIDAQABAoICAEB/p8TmmkcXqxn79RDe1nik
|
|
||||||
QiiE+VrtCaG+Nvq0ym5C+fpzgkWmFYKmYgt1aY38gsS/5LYrFk3+KK1ScDNsly0r
|
|
||||||
aFA+JPKGgrfWxcjJxj1FmXgJFHAe4lL0WOZM7c1NZSiCoxYaBc00Ldc45F0bwSgN
|
|
||||||
cc2Dv6dj3S2vMokfoIVS9hscGW4ExheqJoSM2b+jw2Eo6LhRST7rEGkV+3foAmmf
|
|
||||||
RugLwuQ3YtbCXR7XWKwdCh4A84BAydxV6XV6evUMSS0o90isyvG4kcXWFH+gD0hz
|
|
||||||
sqnXVfel2RaGD/EU0rczp234VGQEc5RdCk9VOgFphtwfRv7AXQtYjWrfdmYuiD1i
|
|
||||||
csiRZxcDgaDbWssBu7oppnbQo0XQ/pynLRJy3Lf9ETIjQ2Xkn6GdoXZY3Phj/XtW
|
|
||||||
N7WSQTSEqRfVt7XwWx0wGXlPimIaYJDXmYFU1A/XESrvDgjjwtVrSojipwr5kdYl
|
|
||||||
XgCjJVGZyNqAavYzuu7qiH7nXGmEtDQRQlbEQS135ukDkKkv2fIOFbX10iIPgIVM
|
|
||||||
Y5dk7Q3gqCWcgcQ/rcR2LLo2H3PdJl0yQnml8rKz2CNpAHp5p4VF66jfsPC0q0qE
|
|
||||||
1ad3JAweX042/k0/XPbwIjPCvDBUIeZei3gu8AotgmaRQWgLb7ICgvavjLnJKn/J
|
|
||||||
VK2PJHKv/eFvEw6l1T85AoIBAQDVeoTOYe9AdAtsj6oqqjci4WZHJ/keO3pbeh4q
|
|
||||||
JKgxzLlyag+8fSGzNkR0RE4f7EF0lnlcRTUpscaes19tmYMzbL84/wmD1SDAjRnG
|
|
||||||
OVFkBHIgmXRnyRGQvP0QbBk3mcJKz+8qi7Mvb3YkSdh9lyYs/JtsPDI0XeQrq9J7
|
|
||||||
ABIHElu9lCMTtUauljoYZH/pHYjpvk22Ijj6f+0dT5MHHYfsEoxIPB7Ow4JS7buT
|
|
||||||
m+O7vlfYZLxSn3OvbdbzGo2IL+AYVDcszSdx6qmHbeu9uMWOvO/YbIX4VyLtzUuc
|
|
||||||
MQad7nBOkiKVrTFXb0b+g1dxvUV3+FreZ1K9oFYy82bomcDZAoIBAQDRD7XxRkGO
|
|
||||||
OSaWkx2FFMLvntAtO06RpshxtU/rv3vDYwYDulrHc3AaJ+P9rWjb7v15P5OpwRYW
|
|
||||||
x1ve8lm8ycKnR6UgD3EYTQkEQkuZ68+ndhVarYCJaelWM9HdhFiWKdPyyrKwcXLr
|
|
||||||
blcTZjnq4WC76YtTdSdZfn0KRoSAxuAmVwfWBI4LxaUeMk3TMxbJ4aPUCjkKEw0m
|
|
||||||
Jie6S6419d+2aVNXjw4KqaPoSREWlUT8U+iVo1xQp5eg3cOIe2lVukqZTqe7j9Ze
|
|
||||||
zP+Gq/RyTk+dvBWcsK/RzhyC73+KD8qAEmdzPAdEwhkxRioTk2PGtU4/K0nDZk3c
|
|
||||||
TNlLdeOcqg0zAoIBAEwV9MuSADHaqk+xDJdUP36BE3D9AD8UN9Huvl2K3x+Qte/f
|
|
||||||
eWhWuPIkv1UpGycpj1K8ZtjKGd6YbBAYIkTv1+E2OxlXXM7N4XR/VdZei3G4W+ze
|
|
||||||
hKyQ71/E2/VEceBtPuBnJ/jj/aNEeLkKUMzCWGrkRYjYE5SyeiZOgSAxsDsxAd2Z
|
|
||||||
tL7Ldzu2c1JKT4SIcEnO9+eYXvJ5McumluKMVet/2NvOAbTz3bks3hQIFazOdIS9
|
|
||||||
splIF3VJErlml1cYqShCq7+eBxcE6hNIzCK8fj0XfeyHEWCnvd0/tFkg6BjV6NU4
|
|
||||||
JHdwWQuur4D60unI6b+OluR5svW+9boHIoB4fFECggEAHeCW6fJWcBLu1toTf+9l
|
|
||||||
pIUXzz8IjXw+bTGySEjHUTcXpvS9AIAY50QIKzrbH4NaKjfRzJLRq1O2Z3hPJtHW
|
|
||||||
xb1RdfF/AjAQN9GZqFexB4eyqZDeK8U9GZqyRWwilONJbQtW2ix8dfUA8L7NTCoF
|
|
||||||
fxVzWewGQZ34FL3bNeQ2KISLlCR2gGwwms4pnSNSAGwE08raN/xdBrSxPMiQDxoi
|
|
||||||
bJlE1eCV6yQvToUSsh2HDGCZfrkn+kbZPp4y0ZCBj0TeYGaDRiTaSBYX9pEgkC1s
|
|
||||||
52f31rrRhbRlErlTitGS6Ra4Phm4GDV9EDOs07teqQlEM3bmRcybF/7LlyMz8jHD
|
|
||||||
TQKCAQEAvjdo48rvwjlj4IKkhkEWP2Qn19bxeQT6lWb9Wtgqar1CIIk9ei74V6xF
|
|
||||||
5cyhw9vCXqxvlDM37n0JRHc0EM70aCE7IFL7WxCmmwGXBwT/PeyIJMaaZippd+Ff
|
|
||||||
QjBx4z6OSsCnzWnM8YPkRwSSCGVk9EDvxQtwS7BmpqSgilHL1/n1yDKAiiGsvAPI
|
|
||||||
uR5WhXzeN/OUHji7Gp5tCxc6Lo4dKqMhQrMFTomUbupw/o4X8TZ0O3hZdzLv9d4Q
|
|
||||||
9LM5nI4JOwB4qEUOY9kFQNjvxwPvrTPj8QuIyPIjPQYWZ4Jw8lNCOK3COPV8H+Rb
|
|
||||||
kO/SCOEdhp17yWQspky/Uo1RC4lKVA==
|
|
||||||
-----END PRIVATE KEY-----
|
|
|
@ -1,30 +0,0 @@
|
||||||
-----BEGIN CERTIFICATE-----
|
|
||||||
MIIFDTCCAvWgAwIBAgIUGd9jmau898T/kGdIeiRCcdXueaowDQYJKoZIhvcNAQEL
|
|
||||||
BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wHhcNMjMxMDA5MTIyMTU2WhcNMjMx
|
|
||||||
MTA4MTIyMTU2WjAWMRQwEgYDVQQDDAtleGFtcGxlLmNvbTCCAiIwDQYJKoZIhvcN
|
|
||||||
AQEBBQADggIPADCCAgoCggIBAK5WIFMY3y0xpDwbzOLEvt24SVMUK4/rBCGYOxfy
|
|
||||||
63hXd4SyFSkMggWQJJfXuHN8jt24GnWl7sp634XPleNtX6u6/GlrC+wKCx8avBcT
|
|
||||||
W9oNUl27LQnJHMu9FJcQtaABtx2WVu8Eq8Yu1jWiCblglYtu2BAmO60yguKzGftd
|
|
||||||
3Th/MxDLhqqHLZmuzHJBIwg25HVDP9UHMNmLgQdDTytvsYxqdB9tpttOzUj8Ye4A
|
|
||||||
zs8N5v+i70Bkc8BKDZ/NqblImG8Ni60eZfzA5Ldv4j5qYjqDc3x8myyPHSvIAQv5
|
|
||||||
z4xu/qZdCEaqHtP76Re0HyHkagsI6DfIa1pbujQ9pwA/VSxp0OwY3XdxYACzK2DU
|
|
||||||
HGqBaToioDdh9/m5zYD5NiZfkrkNXjqyiei/JugUj190qYvigJswjP5Or4vm8ex1
|
|
||||||
SHn/lLoXZEgpAMkgNgl8TtdUI/JOhptCKtCxD8GfbsvRsI7WEP1wZH7Pm131M8bG
|
|
||||||
ubsZRUZn98LnxDhYP9OtWELelSryfuEzMZqSD7BGLsVIlM8hlBeJMv8e0+V5b7XL
|
|
||||||
p3xDzhQjpCbf29W55LlhIKMUKJBbZ96h34vixNSwTRG6Zu9v6xpLpyZftkHN2AmE
|
|
||||||
/0nkWIA4+qzCAJLnDngXmG99uD7JLhKB4qu9kXd0B/7fBbyvTf2wU35H+BCjDFlx
|
|
||||||
hnA7AgMBAAGjUzBRMB0GA1UdDgQWBBSFuG4k9lOlZweMeqvBejQic3Me1zAfBgNV
|
|
||||||
HSMEGDAWgBSFuG4k9lOlZweMeqvBejQic3Me1zAPBgNVHRMBAf8EBTADAQH/MA0G
|
|
||||||
CSqGSIb3DQEBCwUAA4ICAQAjLko9eLBofC9QzF/rm59kOtS6P8fRD0OJKawRdxvP
|
|
||||||
5ClQFz9Q/2I7E1jbXL9y8r8iB31hpfnMT/XYxHAmJXyV+X2jHlnKmhzWpfrHx84V
|
|
||||||
ZYeFIEFlwJHacPU6mVUUnXLwZIt0VWB3RUT9bgbkXFfkg7Qrccl7Blc0458l8wd2
|
|
||||||
mvNgdEGG9Z8VhyaExAHerpOD299llaDTcV+jKLLAboXzDGJsPmMfRu2DWwosfYQJ
|
|
||||||
MIKajyylmGOrAk+8fVTVWOPJBE6AmxDpKtZQO04nQq78PohP/CsibalimOf00Wqb
|
|
||||||
2x05ssWFP71lmdGilaXCp/mkhaVz/G7ZuDSY9AxCPH4+3pTUbMgsfEmLXRTrUo9c
|
|
||||||
B4zz0eDoUiqU9I4TWAHGhnn7b2e6o8ko0baq+PaCSCDK8haL/17CUyMYQBBdhlG6
|
|
||||||
sSR2IBSXkxGQZnhfmQdYwc7Y3IgsJJoN0ZfqnyBY+u/ZOBegcZFuhMiDGILJBgFi
|
|
||||||
QmgQFTozXKkeEzFdWoRn57lgcBABcMHSucnjekk80uLIWIlL36IyYkPbeI6/I0/l
|
|
||||||
ajKftsVEY96hYUXtDBykBpg6gsJXj2gP2FXHW7ngtuI4/mOqI3ltcWh1C83MvM5N
|
|
||||||
zMYfTNtxVM1vyvN1M7b7iMeosvmAIvQE3bFk/pJCHAZPfsu0zmeizPHBgCySygLn
|
|
||||||
JQ==
|
|
||||||
-----END CERTIFICATE-----
|
|
|
@ -1,298 +0,0 @@
|
||||||
use std::io::ErrorKind;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use assert_matches::*;
|
|
||||||
use prometheus::Registry as MetricsRegistry;
|
|
||||||
use quick_xml::events::Event;
|
|
||||||
use quick_xml::NsReader;
|
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
|
||||||
use tokio::io::{ReadHalf as GenericReadHalf, WriteHalf as GenericWriteHalf};
|
|
||||||
use tokio::net::tcp::{ReadHalf, WriteHalf};
|
|
||||||
use tokio::net::TcpStream;
|
|
||||||
use tokio_rustls::client::TlsStream;
|
|
||||||
use tokio_rustls::rustls::client::ServerCertVerifier;
|
|
||||||
use tokio_rustls::rustls::{ClientConfig, ServerName};
|
|
||||||
use tokio_rustls::TlsConnector;
|
|
||||||
|
|
||||||
use lavina_core::repo::{Storage, StorageConfig};
|
|
||||||
use lavina_core::LavinaCore;
|
|
||||||
use projection_xmpp::{launch, RunningServer, ServerConfig};
|
|
||||||
use proto_xmpp::xml::{Continuation, FromXml, Parser};
|
|
||||||
|
|
||||||
pub async fn read_irc_message(reader: &mut BufReader<ReadHalf<'_>>, buf: &mut Vec<u8>) -> Result<usize> {
|
|
||||||
let mut size = 0;
|
|
||||||
let res = reader.read_until(b'\n', buf).await?;
|
|
||||||
size += res;
|
|
||||||
return Ok(size);
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestScope<'a> {
|
|
||||||
reader: NsReader<BufReader<ReadHalf<'a>>>,
|
|
||||||
writer: WriteHalf<'a>,
|
|
||||||
buffer: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TestScope<'a> {
|
|
||||||
fn new(stream: &mut TcpStream) -> TestScope<'_> {
|
|
||||||
let (reader, writer) = stream.split();
|
|
||||||
let reader = NsReader::from_reader(BufReader::new(reader));
|
|
||||||
let buffer = vec![];
|
|
||||||
TestScope { reader, writer, buffer }
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send(&mut self, str: &str) -> Result<()> {
|
|
||||||
self.writer.write_all(str.as_bytes()).await?;
|
|
||||||
self.writer.flush().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn next_xml_event(&mut self) -> Result<Event<'_>> {
|
|
||||||
self.buffer.clear();
|
|
||||||
let event = self.reader.read_event_into_async(&mut self.buffer).await?;
|
|
||||||
Ok(event)
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn read<T: FromXml>(&mut self) -> Result<T> {
|
|
||||||
self.buffer.clear();
|
|
||||||
let (ns, event) = self.reader.read_resolved_event_into_async(&mut self.buffer).await?;
|
|
||||||
let mut parser: Continuation<_, std::result::Result<T, anyhow::Error>> = T::parse().consume(ns, &event);
|
|
||||||
loop {
|
|
||||||
match parser {
|
|
||||||
Continuation::Final(res) => return Ok(res?),
|
|
||||||
Continuation::Continue(next) => {
|
|
||||||
let (ns, event) = self.reader.read_resolved_event_into_async(&mut self.buffer).await?;
|
|
||||||
parser = next.consume(ns, &event);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestScopeTls<'a> {
|
|
||||||
reader: NsReader<BufReader<GenericReadHalf<&'a mut TlsStream<TcpStream>>>>,
|
|
||||||
writer: GenericWriteHalf<&'a mut TlsStream<TcpStream>>,
|
|
||||||
buffer: Vec<u8>,
|
|
||||||
pub timeout: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TestScopeTls<'a> {
|
|
||||||
fn new(stream: &'a mut TlsStream<TcpStream>, buffer: Vec<u8>) -> TestScopeTls<'a> {
|
|
||||||
let (reader, writer) = tokio::io::split(stream);
|
|
||||||
let reader = NsReader::from_reader(BufReader::new(reader));
|
|
||||||
let timeout = Duration::from_millis(100);
|
|
||||||
|
|
||||||
TestScopeTls {
|
|
||||||
reader,
|
|
||||||
writer,
|
|
||||||
buffer,
|
|
||||||
timeout,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn send(&mut self, str: &str) -> Result<()> {
|
|
||||||
self.writer.write_all(str.as_bytes()).await?;
|
|
||||||
self.writer.flush().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn next_xml_event(&mut self) -> Result<Event<'_>> {
|
|
||||||
self.buffer.clear();
|
|
||||||
let event = self.reader.read_event_into_async(&mut self.buffer);
|
|
||||||
let event = tokio::time::timeout(self.timeout, event).await??;
|
|
||||||
Ok(event)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct IgnoreCertVerification;
|
|
||||||
impl ServerCertVerifier for IgnoreCertVerification {
|
|
||||||
fn verify_server_cert(
|
|
||||||
&self,
|
|
||||||
_end_entity: &tokio_rustls::rustls::Certificate,
|
|
||||||
_intermediates: &[tokio_rustls::rustls::Certificate],
|
|
||||||
_server_name: &ServerName,
|
|
||||||
_scts: &mut dyn Iterator<Item = &[u8]>,
|
|
||||||
_ocsp_response: &[u8],
|
|
||||||
_now: std::time::SystemTime,
|
|
||||||
) -> std::result::Result<tokio_rustls::rustls::client::ServerCertVerified, tokio_rustls::rustls::Error> {
|
|
||||||
Ok(tokio_rustls::rustls::client::ServerCertVerified::assertion())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestServer {
|
|
||||||
metrics: MetricsRegistry,
|
|
||||||
storage: Storage,
|
|
||||||
core: LavinaCore,
|
|
||||||
server: RunningServer,
|
|
||||||
}
|
|
||||||
impl TestServer {
|
|
||||||
async fn start() -> Result<TestServer> {
|
|
||||||
let _ = 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(),
|
|
||||||
hostname: "localhost".into(),
|
|
||||||
};
|
|
||||||
let metrics = MetricsRegistry::new();
|
|
||||||
let storage = Storage::open(StorageConfig {
|
|
||||||
db_path: ":memory:".into(),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
let core = LavinaCore::new(metrics.clone(), storage.clone()).await?;
|
|
||||||
let server = launch(config, core.clone(), metrics.clone(), storage.clone()).await.unwrap();
|
|
||||||
Ok(TestServer {
|
|
||||||
metrics,
|
|
||||||
storage,
|
|
||||||
core,
|
|
||||||
server,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_basic() -> 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);
|
|
||||||
tracing::info!("TCP connection established");
|
|
||||||
|
|
||||||
s.send(r#"<?xml version="1.0"?>"#).await?;
|
|
||||||
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"required"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
s.send(r#"<starttls/>"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
|
|
||||||
let buffer = s.buffer;
|
|
||||||
tracing::info!("TLS feature negotiation complete");
|
|
||||||
|
|
||||||
let connector = TlsConnector::from(Arc::new(
|
|
||||||
ClientConfig::builder()
|
|
||||||
.with_safe_defaults()
|
|
||||||
.with_custom_certificate_verifier(Arc::new(IgnoreCertVerification))
|
|
||||||
.with_no_client_auth(),
|
|
||||||
));
|
|
||||||
tracing::info!("Initiating TLS connection...");
|
|
||||||
let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
|
|
||||||
tracing::info!("TLS connection established");
|
|
||||||
|
|
||||||
let mut s = TestScopeTls::new(&mut stream, buffer);
|
|
||||||
|
|
||||||
s.send(r#"<?xml version="1.0"?>"#).await?;
|
|
||||||
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
|
|
||||||
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// wrap up
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn scenario_basic_without_headers() -> 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);
|
|
||||||
tracing::info!("TCP connection established");
|
|
||||||
|
|
||||||
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"required"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
s.send(r#"<starttls/>"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
|
|
||||||
let buffer = s.buffer;
|
|
||||||
tracing::info!("TLS feature negotiation complete");
|
|
||||||
|
|
||||||
let connector = TlsConnector::from(Arc::new(
|
|
||||||
ClientConfig::builder()
|
|
||||||
.with_safe_defaults()
|
|
||||||
.with_custom_certificate_verifier(Arc::new(IgnoreCertVerification))
|
|
||||||
.with_no_client_auth(),
|
|
||||||
));
|
|
||||||
tracing::info!("Initiating TLS connection...");
|
|
||||||
let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
|
|
||||||
tracing::info!("TLS connection established");
|
|
||||||
|
|
||||||
let mut s = TestScopeTls::new(&mut stream, buffer);
|
|
||||||
|
|
||||||
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
|
|
||||||
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// wrap up
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn terminate_socket() -> 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);
|
|
||||||
tracing::info!("TCP connection established");
|
|
||||||
|
|
||||||
s.send(r#"<?xml version="1.0"?>"#).await?;
|
|
||||||
|
|
||||||
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"required"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
s.send(r#"<starttls/>"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
|
|
||||||
|
|
||||||
let connector = TlsConnector::from(Arc::new(
|
|
||||||
ClientConfig::builder()
|
|
||||||
.with_safe_defaults()
|
|
||||||
.with_custom_certificate_verifier(Arc::new(IgnoreCertVerification))
|
|
||||||
.with_no_client_auth(),
|
|
||||||
));
|
|
||||||
|
|
||||||
tracing::info!("Initiating TLS connection...");
|
|
||||||
let mut stream = connector.connect(ServerName::IpAddress(server.server.addr.ip()), stream).await?;
|
|
||||||
tracing::info!("TLS connection established");
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
|
|
||||||
assert_eq!(stream.read_u8().await.unwrap_err().kind(), ErrorKind::UnexpectedEof);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
|
@ -1,70 +1,67 @@
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use nom::combinator::opt;
|
||||||
use nom::combinator::{all_consuming, opt};
|
|
||||||
use nonempty::NonEmpty;
|
|
||||||
|
|
||||||
/// Client-to-server command.
|
/// Client-to-server command.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum ClientMessage {
|
pub enum ClientMessage {
|
||||||
/// `CAP`. Capability-related commands.
|
/// CAP. Capability-related commands.
|
||||||
Capability {
|
Capability {
|
||||||
subcommand: CapabilitySubcommand,
|
subcommand: CapabilitySubcommand,
|
||||||
},
|
},
|
||||||
/// `PING <token>`
|
/// PING <token>
|
||||||
Ping {
|
Ping {
|
||||||
token: Str,
|
token: Str,
|
||||||
},
|
},
|
||||||
/// `PONG <token>`
|
/// PONG <token>
|
||||||
Pong {
|
Pong {
|
||||||
token: Str,
|
token: Str,
|
||||||
},
|
},
|
||||||
/// `NICK <nickname>`
|
/// NICK <nickname>
|
||||||
Nick {
|
Nick {
|
||||||
nickname: Str,
|
nickname: Str,
|
||||||
},
|
},
|
||||||
/// `PASS <password>`
|
/// PASS <password>
|
||||||
Pass {
|
Pass {
|
||||||
password: Str,
|
password: Str,
|
||||||
},
|
},
|
||||||
/// `USER <username> 0 * :<realname>`
|
/// USER <username> 0 * :<realname>
|
||||||
User {
|
User {
|
||||||
username: Str,
|
username: Str,
|
||||||
realname: Str,
|
realname: Str,
|
||||||
},
|
},
|
||||||
/// `JOIN <chan>`
|
/// JOIN <chan>
|
||||||
Join(Chan),
|
Join(Chan),
|
||||||
/// `MODE <target>`
|
/// MODE <target>
|
||||||
Mode {
|
Mode {
|
||||||
target: Recipient,
|
target: Recipient,
|
||||||
},
|
},
|
||||||
/// `WHO <target>`
|
/// WHO <target>
|
||||||
Who {
|
Who {
|
||||||
target: Recipient, // aka mask
|
target: Recipient, // aka mask
|
||||||
},
|
},
|
||||||
/// `TOPIC <chan> :<topic>`
|
/// TOPIC <chan> :<topic>
|
||||||
Topic {
|
Topic {
|
||||||
chan: Chan,
|
chan: Chan,
|
||||||
topic: Str,
|
topic: Str,
|
||||||
},
|
},
|
||||||
Part {
|
Part {
|
||||||
chan: Chan,
|
chan: Chan,
|
||||||
message: Option<Str>,
|
message: Str,
|
||||||
},
|
},
|
||||||
/// `PRIVMSG <target> :<msg>`
|
/// PRIVMSG <target> :<msg>
|
||||||
PrivateMessage {
|
PrivateMessage {
|
||||||
recipient: Recipient,
|
recipient: Recipient,
|
||||||
body: Str,
|
body: Str,
|
||||||
},
|
},
|
||||||
/// `QUIT :<reason>`
|
/// QUIT :<reason>
|
||||||
Quit {
|
Quit {
|
||||||
reason: Str,
|
reason: Str,
|
||||||
},
|
},
|
||||||
Authenticate(Str),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn client_message(input: &str) -> Result<ClientMessage> {
|
pub fn client_message(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
let res = all_consuming(alt((
|
alt((
|
||||||
client_message_capability,
|
client_message_capability,
|
||||||
client_message_ping,
|
client_message_ping,
|
||||||
client_message_pong,
|
client_message_pong,
|
||||||
|
@ -78,12 +75,7 @@ pub fn client_message(input: &str) -> Result<ClientMessage> {
|
||||||
client_message_part,
|
client_message_part,
|
||||||
client_message_privmsg,
|
client_message_privmsg,
|
||||||
client_message_quit,
|
client_message_quit,
|
||||||
client_message_authenticate,
|
))(input)
|
||||||
)))(input);
|
|
||||||
match res {
|
|
||||||
Ok((_, e)) => Ok(e),
|
|
||||||
Err(e) => Err(anyhow!("Parsing failed: {e}")),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_message_capability(input: &str) -> IResult<&str, ClientMessage> {
|
fn client_message_capability(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
|
@ -97,14 +89,24 @@ fn client_message_ping(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
let (input, _) = tag("PING ")(input)?;
|
let (input, _) = tag("PING ")(input)?;
|
||||||
let (input, token) = token(input)?;
|
let (input, token) = token(input)?;
|
||||||
|
|
||||||
Ok((input, ClientMessage::Ping { token: token.into() }))
|
Ok((
|
||||||
|
input,
|
||||||
|
ClientMessage::Ping {
|
||||||
|
token: token.into(),
|
||||||
|
},
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_message_pong(input: &str) -> IResult<&str, ClientMessage> {
|
fn client_message_pong(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
let (input, _) = tag("PONG ")(input)?;
|
let (input, _) = tag("PONG ")(input)?;
|
||||||
let (input, token) = token(input)?;
|
let (input, token) = token(input)?;
|
||||||
|
|
||||||
Ok((input, ClientMessage::Pong { token: token.into() }))
|
Ok((
|
||||||
|
input,
|
||||||
|
ClientMessage::Pong {
|
||||||
|
token: token.into(),
|
||||||
|
},
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_message_nick(input: &str) -> IResult<&str, ClientMessage> {
|
fn client_message_nick(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
|
@ -194,20 +196,14 @@ fn client_message_topic(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
fn client_message_part(input: &str) -> IResult<&str, ClientMessage> {
|
fn client_message_part(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
let (input, _) = tag("PART ")(input)?;
|
let (input, _) = tag("PART ")(input)?;
|
||||||
let (input, chan) = chan(input)?;
|
let (input, chan) = chan(input)?;
|
||||||
let (input, t) = opt(tag(" "))(input)?;
|
let (input, _) = tag(" ")(input)?;
|
||||||
match t {
|
|
||||||
Some(_) => (),
|
|
||||||
None => {
|
|
||||||
return Ok((input, ClientMessage::Part { chan, message: None }));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let (input, r) = opt(tag(":"))(input)?;
|
let (input, r) = opt(tag(":"))(input)?;
|
||||||
let (input, message) = match r {
|
let (input, message) = match r {
|
||||||
Some(_) => token(input)?,
|
Some(_) => token(input)?,
|
||||||
None => receiver(input)?,
|
None => receiver(input)?,
|
||||||
};
|
};
|
||||||
|
|
||||||
let message = Some(message.into());
|
let message = message.into();
|
||||||
Ok((input, ClientMessage::Part { chan, message }))
|
Ok((input, ClientMessage::Part { chan, message }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -229,32 +225,24 @@ fn client_message_quit(input: &str) -> IResult<&str, ClientMessage> {
|
||||||
let (input, _) = tag("QUIT :")(input)?;
|
let (input, _) = tag("QUIT :")(input)?;
|
||||||
let (input, reason) = token(input)?;
|
let (input, reason) = token(input)?;
|
||||||
|
|
||||||
Ok((input, ClientMessage::Quit { reason: reason.into() }))
|
Ok((
|
||||||
}
|
input,
|
||||||
|
ClientMessage::Quit {
|
||||||
fn client_message_authenticate(input: &str) -> IResult<&str, ClientMessage> {
|
reason: reason.into(),
|
||||||
let (input, _) = tag("AUTHENTICATE ")(input)?;
|
},
|
||||||
let (input, body) = token(input)?;
|
))
|
||||||
|
|
||||||
Ok((input, ClientMessage::Authenticate(body.into())))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum CapabilitySubcommand {
|
pub enum CapabilitySubcommand {
|
||||||
/// CAP LS {code}
|
/// CAP LS {code}
|
||||||
List { code: [u8; 3] },
|
List { code: [u8; 3] },
|
||||||
/// CAP REQ :...
|
|
||||||
Req(NonEmpty<CapReq>),
|
|
||||||
/// CAP END
|
/// CAP END
|
||||||
End,
|
End,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn capability_subcommand(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
fn capability_subcommand(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
alt((
|
alt((capability_subcommand_ls, capability_subcommand_end))(input)
|
||||||
capability_subcommand_ls,
|
|
||||||
capability_subcommand_end,
|
|
||||||
capability_subcommand_req,
|
|
||||||
))(input)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn capability_subcommand_ls(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
fn capability_subcommand_ls(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
|
@ -269,46 +257,14 @@ fn capability_subcommand_ls(input: &str) -> IResult<&str, CapabilitySubcommand>
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn capability_subcommand_req(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
|
||||||
let (input, _) = tag("REQ ")(input)?;
|
|
||||||
let (input, r) = opt(tag(":"))(input)?;
|
|
||||||
let (input, body) = match r {
|
|
||||||
Some(_) => token(input)?,
|
|
||||||
None => receiver(input)?,
|
|
||||||
};
|
|
||||||
|
|
||||||
let caps = body
|
|
||||||
.split(' ')
|
|
||||||
.map(|cap| {
|
|
||||||
let to_disable = cap.starts_with('-');
|
|
||||||
let name = if to_disable { &cap[1..] } else { &cap[..] };
|
|
||||||
CapReq {
|
|
||||||
to_disable,
|
|
||||||
name: name.into(),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
let caps = NonEmpty::from_vec(caps).ok_or_else(|| todo!())?;
|
|
||||||
|
|
||||||
Ok((input, CapabilitySubcommand::Req(caps)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn capability_subcommand_end(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
fn capability_subcommand_end(input: &str) -> IResult<&str, CapabilitySubcommand> {
|
||||||
let (input, _) = tag("END")(input)?;
|
let (input, _) = tag("END")(input)?;
|
||||||
Ok((input, CapabilitySubcommand::End))
|
Ok((input, CapabilitySubcommand::End))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct CapReq {
|
|
||||||
pub to_disable: bool,
|
|
||||||
pub name: Str,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use assert_matches::*;
|
use assert_matches::*;
|
||||||
use nonempty::nonempty;
|
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -319,7 +275,7 @@ mod test {
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -330,24 +286,28 @@ mod test {
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_client_message_ping() {
|
fn test_client_message_ping() {
|
||||||
let input = "PING 1337";
|
let input = "PING 1337";
|
||||||
let expected = ClientMessage::Ping { token: "1337".into() };
|
let expected = ClientMessage::Ping {
|
||||||
|
token: "1337".into(),
|
||||||
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn test_client_message_pong() {
|
fn test_client_message_pong() {
|
||||||
let input = "PONG 1337";
|
let input = "PONG 1337";
|
||||||
let expected = ClientMessage::Pong { token: "1337".into() };
|
let expected = ClientMessage::Pong {
|
||||||
|
token: "1337".into(),
|
||||||
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn test_client_message_nick() {
|
fn test_client_message_nick() {
|
||||||
|
@ -357,7 +317,7 @@ mod test {
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn test_client_message_user() {
|
fn test_client_message_user() {
|
||||||
|
@ -368,47 +328,17 @@ mod test {
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn test_client_message_part() {
|
fn test_client_message_part() {
|
||||||
let input = "PART #chan :Pokasiki !!!";
|
let input = "PART #chan :Pokasiki !!!";
|
||||||
let expected = ClientMessage::Part {
|
let expected = ClientMessage::Part {
|
||||||
chan: Chan::Global("chan".into()),
|
chan: Chan::Global("chan".into()),
|
||||||
message: Some("Pokasiki !!!".into()),
|
message: "Pokasiki !!!".into(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let result = client_message(input);
|
let result = client_message(input);
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn test_client_message_part_empty() {
|
|
||||||
let input = "PART #chan";
|
|
||||||
let expected = ClientMessage::Part {
|
|
||||||
chan: Chan::Global("chan".into()),
|
|
||||||
message: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = client_message(input);
|
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
|
||||||
}
|
|
||||||
#[test]
|
|
||||||
fn test_client_cap_req() {
|
|
||||||
let input = "CAP REQ :multi-prefix -sasl";
|
|
||||||
let expected = ClientMessage::Capability {
|
|
||||||
subcommand: CapabilitySubcommand::Req(nonempty![
|
|
||||||
CapReq {
|
|
||||||
to_disable: false,
|
|
||||||
name: "multi-prefix".into()
|
|
||||||
},
|
|
||||||
CapReq {
|
|
||||||
to_disable: true,
|
|
||||||
name: "sasl".into()
|
|
||||||
}
|
|
||||||
]),
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = client_message(input);
|
|
||||||
assert_matches!(result, Ok(result) => assert_eq!(expected, result));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,7 @@ mod testkit;
|
||||||
pub mod user;
|
pub mod user;
|
||||||
|
|
||||||
use crate::prelude::Str;
|
use crate::prelude::Str;
|
||||||
|
use std::io::Result;
|
||||||
|
|
||||||
use nom::{
|
use nom::{
|
||||||
branch::alt,
|
branch::alt,
|
||||||
|
@ -30,19 +31,15 @@ fn token(input: &str) -> IResult<&str, &str> {
|
||||||
take_while(|i| i != '\n' && i != '\r')(input)
|
take_while(|i| i != '\n' && i != '\r')(input)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn params(input: &str) -> IResult<&str, &str> {
|
|
||||||
take_while(|i| i != '\n' && i != '\r' && i != ':')(input)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum Chan {
|
pub enum Chan {
|
||||||
/// `#<name>` — network-global channel, available from any server in the network.
|
/// #<name> — network-global channel, available from any server in the network.
|
||||||
Global(Str),
|
Global(Str),
|
||||||
/// `&<name>` — server-local channel, available only to connections to the same server. Rarely used in practice.
|
/// &<name> — server-local channel, available only to connections to the same server. Rarely used in practice.
|
||||||
Local(Str),
|
Local(Str),
|
||||||
}
|
}
|
||||||
impl Chan {
|
impl Chan {
|
||||||
pub async fn write_async(&self, writer: &mut (impl AsyncWrite + Unpin)) -> std::io::Result<()> {
|
pub async fn write_async(&self, writer: &mut (impl AsyncWrite + Unpin)) -> Result<()> {
|
||||||
match self {
|
match self {
|
||||||
Chan::Global(name) => {
|
Chan::Global(name) => {
|
||||||
writer.write_all(b"#").await?;
|
writer.write_all(b"#").await?;
|
||||||
|
@ -79,7 +76,7 @@ pub enum Recipient {
|
||||||
Chan(Chan),
|
Chan(Chan),
|
||||||
}
|
}
|
||||||
impl Recipient {
|
impl Recipient {
|
||||||
pub async fn write_async(&self, writer: &mut (impl AsyncWrite + Unpin)) -> std::io::Result<()> {
|
pub async fn write_async(&self, writer: &mut (impl AsyncWrite + Unpin)) -> Result<()> {
|
||||||
match self {
|
match self {
|
||||||
Recipient::Nick(nick) => writer.write_all(nick.as_bytes()).await?,
|
Recipient::Nick(nick) => writer.write_all(nick.as_bytes()).await?,
|
||||||
Recipient::Chan(chan) => chan.write_async(writer).await?,
|
Recipient::Chan(chan) => chan.write_async(writer).await?,
|
||||||
|
@ -118,7 +115,9 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
sync_future(expected.write_async(&mut bytes))
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(bytes.as_slice(), input.as_bytes());
|
assert_eq!(bytes.as_slice(), input.as_bytes());
|
||||||
}
|
}
|
||||||
|
@ -132,7 +131,9 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
sync_future(expected.write_async(&mut bytes))
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(bytes.as_slice(), input.as_bytes());
|
assert_eq!(bytes.as_slice(), input.as_bytes());
|
||||||
}
|
}
|
||||||
|
@ -146,7 +147,9 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
sync_future(expected.write_async(&mut bytes))
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
assert_eq!(bytes.as_slice(), input.as_bytes());
|
assert_eq!(bytes.as_slice(), input.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use nonempty::NonEmpty;
|
use nonempty::NonEmpty;
|
||||||
use tokio::io::AsyncWrite;
|
use tokio::io::AsyncWrite;
|
||||||
use tokio::io::AsyncWriteExt;
|
use tokio::io::AsyncWriteExt;
|
||||||
|
@ -68,11 +66,6 @@ pub enum ServerMessageBody {
|
||||||
Error {
|
Error {
|
||||||
reason: Str,
|
reason: Str,
|
||||||
},
|
},
|
||||||
Cap {
|
|
||||||
target: Str,
|
|
||||||
subcmd: CapSubBody,
|
|
||||||
},
|
|
||||||
Authenticate(Str),
|
|
||||||
N001Welcome {
|
N001Welcome {
|
||||||
client: Str,
|
client: Str,
|
||||||
text: Str,
|
text: Str,
|
||||||
|
@ -145,20 +138,6 @@ pub enum ServerMessageBody {
|
||||||
client: Str,
|
client: Str,
|
||||||
message: Str,
|
message: Str,
|
||||||
},
|
},
|
||||||
N900LoggedIn {
|
|
||||||
nick: Str,
|
|
||||||
address: Str,
|
|
||||||
account: Str,
|
|
||||||
message: Str,
|
|
||||||
},
|
|
||||||
N903SaslSuccess {
|
|
||||||
nick: Str,
|
|
||||||
message: Str,
|
|
||||||
},
|
|
||||||
N904SaslFail {
|
|
||||||
nick: Str,
|
|
||||||
text: Str,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ServerMessageBody {
|
impl ServerMessageBody {
|
||||||
|
@ -202,24 +181,6 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b"ERROR :").await?;
|
writer.write_all(b"ERROR :").await?;
|
||||||
writer.write_all(reason.as_bytes()).await?;
|
writer.write_all(reason.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
ServerMessageBody::Cap { target, subcmd } => {
|
|
||||||
writer.write_all(b"CAP ").await?;
|
|
||||||
writer.write_all(target.as_bytes()).await?;
|
|
||||||
match subcmd {
|
|
||||||
CapSubBody::Ls(caps) => {
|
|
||||||
writer.write_all(b" LS :").await?;
|
|
||||||
writer.write_all(caps.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
CapSubBody::Ack(caps) => {
|
|
||||||
writer.write_all(b" ACK :").await?;
|
|
||||||
writer.write_all(caps.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ServerMessageBody::Authenticate(body) => {
|
|
||||||
writer.write_all(b"AUTHENTICATE ").await?;
|
|
||||||
writer.write_all(body.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
ServerMessageBody::N001Welcome { client, text } => {
|
ServerMessageBody::N001Welcome { client, text } => {
|
||||||
writer.write_all(b"001 ").await?;
|
writer.write_all(b"001 ").await?;
|
||||||
writer.write_all(client.as_bytes()).await?;
|
writer.write_all(client.as_bytes()).await?;
|
||||||
|
@ -273,7 +234,11 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b" :").await?;
|
writer.write_all(b" :").await?;
|
||||||
writer.write_all(msg.as_bytes()).await?;
|
writer.write_all(msg.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
ServerMessageBody::N332Topic { client, chat, topic } => {
|
ServerMessageBody::N332Topic {
|
||||||
|
client,
|
||||||
|
chat,
|
||||||
|
topic,
|
||||||
|
} => {
|
||||||
writer.write_all(b"332 ").await?;
|
writer.write_all(b"332 ").await?;
|
||||||
writer.write_all(client.as_bytes()).await?;
|
writer.write_all(client.as_bytes()).await?;
|
||||||
writer.write_all(b" ").await?;
|
writer.write_all(b" ").await?;
|
||||||
|
@ -311,21 +276,22 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b" ").await?;
|
writer.write_all(b" ").await?;
|
||||||
writer.write_all(realname.as_bytes()).await?;
|
writer.write_all(realname.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
ServerMessageBody::N353NamesReply { client, chan, members } => {
|
ServerMessageBody::N353NamesReply {
|
||||||
|
client,
|
||||||
|
chan,
|
||||||
|
members,
|
||||||
|
} => {
|
||||||
writer.write_all(b"353 ").await?;
|
writer.write_all(b"353 ").await?;
|
||||||
writer.write_all(client.as_bytes()).await?;
|
writer.write_all(client.as_bytes()).await?;
|
||||||
writer.write_all(b" = ").await?;
|
writer.write_all(b" = ").await?;
|
||||||
chan.write_async(writer).await?;
|
chan.write_async(writer).await?;
|
||||||
writer.write_all(b" :").await?;
|
writer.write_all(b" :").await?;
|
||||||
{
|
for member in members {
|
||||||
let member = &members.head;
|
writer
|
||||||
writer.write_all(member.prefix.to_string().as_bytes()).await?;
|
.write_all(member.prefix.to_string().as_bytes())
|
||||||
|
.await?;
|
||||||
writer.write_all(member.nick.as_bytes()).await?;
|
writer.write_all(member.nick.as_bytes()).await?;
|
||||||
}
|
|
||||||
for member in &members.tail {
|
|
||||||
writer.write_all(b" ").await?;
|
writer.write_all(b" ").await?;
|
||||||
writer.write_all(member.prefix.to_string().as_bytes()).await?;
|
|
||||||
writer.write_all(member.nick.as_bytes()).await?;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ServerMessageBody::N366NamesReplyEnd { client, chan } => {
|
ServerMessageBody::N366NamesReplyEnd { client, chan } => {
|
||||||
|
@ -335,7 +301,11 @@ impl ServerMessageBody {
|
||||||
chan.write_async(writer).await?;
|
chan.write_async(writer).await?;
|
||||||
writer.write_all(b" :End of /NAMES list").await?;
|
writer.write_all(b" :End of /NAMES list").await?;
|
||||||
}
|
}
|
||||||
ServerMessageBody::N474BannedFromChan { client, chan, message } => {
|
ServerMessageBody::N474BannedFromChan {
|
||||||
|
client,
|
||||||
|
chan,
|
||||||
|
message,
|
||||||
|
} => {
|
||||||
writer.write_all(b"474 ").await?;
|
writer.write_all(b"474 ").await?;
|
||||||
writer.write_all(client.as_bytes()).await?;
|
writer.write_all(client.as_bytes()).await?;
|
||||||
writer.write_all(b" ").await?;
|
writer.write_all(b" ").await?;
|
||||||
|
@ -350,45 +320,11 @@ impl ServerMessageBody {
|
||||||
writer.write_all(b" :").await?;
|
writer.write_all(b" :").await?;
|
||||||
writer.write_all(message.as_bytes()).await?;
|
writer.write_all(message.as_bytes()).await?;
|
||||||
}
|
}
|
||||||
ServerMessageBody::N900LoggedIn {
|
|
||||||
nick,
|
|
||||||
address,
|
|
||||||
account,
|
|
||||||
message,
|
|
||||||
} => {
|
|
||||||
writer.write_all(b"900 ").await?;
|
|
||||||
writer.write_all(nick.as_bytes()).await?;
|
|
||||||
writer.write_all(b" ").await?;
|
|
||||||
writer.write_all(address.as_bytes()).await?;
|
|
||||||
writer.write_all(b" ").await?;
|
|
||||||
writer.write_all(account.as_bytes()).await?;
|
|
||||||
writer.write_all(b" :").await?;
|
|
||||||
writer.write_all(message.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
ServerMessageBody::N903SaslSuccess { nick, message } => {
|
|
||||||
writer.write_all(b"903 ").await?;
|
|
||||||
writer.write_all(nick.as_bytes()).await?;
|
|
||||||
writer.write_all(b" :").await?;
|
|
||||||
writer.write_all(message.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
ServerMessageBody::N904SaslFail { nick, text } => {
|
|
||||||
writer.write_all(b"904").await?;
|
|
||||||
writer.write_all(b" ").await?;
|
|
||||||
writer.write_all(nick.as_bytes()).await?;
|
|
||||||
writer.write_all(b" :").await?;
|
|
||||||
writer.write_all(text.as_bytes()).await?;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum CapSubBody {
|
|
||||||
Ls(Str),
|
|
||||||
Ack(Str),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub enum AwayStatus {
|
pub enum AwayStatus {
|
||||||
Here,
|
Here,
|
||||||
|
@ -400,7 +336,6 @@ fn server_message_body(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
server_message_body_notice,
|
server_message_body_notice,
|
||||||
server_message_body_ping,
|
server_message_body_ping,
|
||||||
server_message_body_pong,
|
server_message_body_pong,
|
||||||
server_message_body_cap,
|
|
||||||
))(input)
|
))(input)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -426,7 +361,12 @@ fn server_message_body_ping(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
let (input, _) = tag("PING ")(input)?;
|
let (input, _) = tag("PING ")(input)?;
|
||||||
let (input, token) = token(input)?;
|
let (input, token) = token(input)?;
|
||||||
|
|
||||||
Ok((input, ServerMessageBody::Ping { token: token.into() }))
|
Ok((
|
||||||
|
input,
|
||||||
|
ServerMessageBody::Ping {
|
||||||
|
token: token.into(),
|
||||||
|
},
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn server_message_body_pong(input: &str) -> IResult<&str, ServerMessageBody> {
|
fn server_message_body_pong(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
|
@ -444,21 +384,6 @@ fn server_message_body_pong(input: &str) -> IResult<&str, ServerMessageBody> {
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn server_message_body_cap(input: &str) -> IResult<&str, ServerMessageBody> {
|
|
||||||
let (input, _) = tag("CAP ")(input)?;
|
|
||||||
let (input, from) = receiver(input)?;
|
|
||||||
let (input, _) = tag(" LS :")(input)?;
|
|
||||||
let (input, token) = token(input)?;
|
|
||||||
|
|
||||||
Ok((
|
|
||||||
input,
|
|
||||||
ServerMessageBody::Cap {
|
|
||||||
target: from.into(),
|
|
||||||
subcmd: CapSubBody::Ls(token.into()),
|
|
||||||
},
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use assert_matches::*;
|
use assert_matches::*;
|
||||||
|
@ -483,7 +408,9 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
sync_future(expected.write_async(&mut bytes))
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
assert_eq!(bytes, input.as_bytes());
|
assert_eq!(bytes, input.as_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -503,27 +430,9 @@ mod test {
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
||||||
|
|
||||||
let mut bytes = vec![];
|
let mut bytes = vec![];
|
||||||
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
sync_future(expected.write_async(&mut bytes))
|
||||||
assert_eq!(bytes, input.as_bytes());
|
.unwrap()
|
||||||
}
|
.unwrap();
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_server_message_cap_ls() {
|
|
||||||
let input = "CAP * LS :sasl\r\n";
|
|
||||||
let expected = ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: None,
|
|
||||||
body: ServerMessageBody::Cap {
|
|
||||||
target: "*".into(),
|
|
||||||
subcmd: CapSubBody::Ls("sasl".into()),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = server_message(input);
|
|
||||||
assert_matches!(result, Ok((_, result)) => assert_eq!(expected, result));
|
|
||||||
|
|
||||||
let mut bytes = vec![];
|
|
||||||
sync_future(expected.write_async(&mut bytes)).unwrap().unwrap();
|
|
||||||
assert_eq!(bytes, input.as_bytes());
|
assert_eq!(bytes, input.as_bytes());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,6 +10,3 @@ regex.workspace = true
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
derive_more.workspace = true
|
derive_more.workspace = true
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
assert_matches.workspace = true
|
|
||||||
|
|
|
@ -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);
|
||||||
|
|
||||||
|
@ -45,19 +42,27 @@ impl Display for Jid {
|
||||||
|
|
||||||
impl Jid {
|
impl Jid {
|
||||||
pub fn from_string(i: &str) -> Result<Jid> {
|
pub fn from_string(i: &str) -> Result<Jid> {
|
||||||
use lazy_static::lazy_static;
|
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
|
use lazy_static::lazy_static;
|
||||||
lazy_static! {
|
lazy_static! {
|
||||||
static ref RE: Regex = Regex::new(r"^(([a-zA-Z0-9]+)@)?([^@/]+)(/([a-zA-Z0-9\-]+))?$").unwrap();
|
static ref RE: Regex = Regex::new(r"^(([a-zA-Z]+)@)?([a-zA-Z.]+)(/([a-zA-Z\-]+))?$").unwrap();
|
||||||
}
|
}
|
||||||
let m = RE.captures(i).ok_or(anyhow!("Incorrectly format jid: {i}"))?;
|
let m = RE
|
||||||
|
.captures(i)
|
||||||
|
.ok_or(anyhow!("Incorrectly format jid: {i}"))?;
|
||||||
|
|
||||||
let name = m.get(2).map(|name| Name(name.as_str().into()));
|
let name = m.get(2).map(|name| Name(name.as_str().into()));
|
||||||
let server = m.get(3).unwrap();
|
let server = m.get(3).unwrap();
|
||||||
let server = Server(server.as_str().into());
|
let server = Server(server.as_str().into());
|
||||||
let resource = m.get(5).map(|resource| Resource(resource.as_str().into()));
|
let resource = m
|
||||||
|
.get(5)
|
||||||
|
.map(|resource| Resource(resource.as_str().into()));
|
||||||
|
|
||||||
Ok(Jid { name, server, resource })
|
Ok(Jid {
|
||||||
|
name,
|
||||||
|
server,
|
||||||
|
resource,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -132,7 +137,9 @@ pub struct BindResponse(pub Jid);
|
||||||
impl ToXml for BindResponse {
|
impl ToXml for BindResponse {
|
||||||
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
||||||
events.extend_from_slice(&[
|
events.extend_from_slice(&[
|
||||||
Event::Start(BytesStart::new(r#"bind xmlns="urn:ietf:params:xml:ns:xmpp-bind""#)),
|
Event::Start(BytesStart::new(
|
||||||
|
r#"bind xmlns="urn:ietf:params:xml:ns:xmpp-bind""#,
|
||||||
|
)),
|
||||||
Event::Start(BytesStart::new(r#"jid"#)),
|
Event::Start(BytesStart::new(r#"jid"#)),
|
||||||
Event::Text(BytesText::new(self.0.to_string().as_str()).into_owned()),
|
Event::Text(BytesText::new(self.0.to_string().as_str()).into_owned()),
|
||||||
Event::End(BytesEnd::new("jid")),
|
Event::End(BytesEnd::new("jid")),
|
||||||
|
@ -149,16 +156,23 @@ mod tests {
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn parse_message() {
|
async fn parse_message() {
|
||||||
let input = r#"<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>mobile</resource></bind>"#;
|
let input =
|
||||||
|
r#"<bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"><resource>mobile</resource></bind>"#;
|
||||||
let mut reader = NsReader::from_reader(input.as_bytes());
|
let mut reader = NsReader::from_reader(input.as_bytes());
|
||||||
let mut buf = vec![];
|
let mut buf = vec![];
|
||||||
let (ns, event) = reader.read_resolved_event_into_async(&mut buf).await.unwrap();
|
let (ns, event) = reader
|
||||||
|
.read_resolved_event_into_async(&mut buf)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
let mut parser = BindRequest::parse().consume(ns, &event);
|
let mut parser = BindRequest::parse().consume(ns, &event);
|
||||||
let result = loop {
|
let result = loop {
|
||||||
match parser {
|
match parser {
|
||||||
Continuation::Final(res) => break res,
|
Continuation::Final(res) => break res,
|
||||||
Continuation::Continue(next) => {
|
Continuation::Continue(next) => {
|
||||||
let (ns, event) = reader.read_resolved_event_into_async(&mut buf).await.unwrap();
|
let (ns, event) = reader
|
||||||
|
.read_resolved_event_into_async(&mut buf)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
parser = next.consume(ns, &event);
|
parser = next.consume(ns, &event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -255,49 +255,11 @@ impl MessageType {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Error response to an IQ request.
|
|
||||||
///
|
|
||||||
/// https://xmpp.org/rfcs/rfc6120.html#stanzas-error
|
|
||||||
pub struct IqError {
|
|
||||||
pub r#type: IqErrorType,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub enum IqErrorType {
|
|
||||||
/// Retry after providing credentials
|
|
||||||
Auth,
|
|
||||||
/// Do not retry (the error cannot be remedied)
|
|
||||||
Cancel,
|
|
||||||
/// Proceed (the condition was only a warning)
|
|
||||||
Continue,
|
|
||||||
/// Retry after changing the data sent
|
|
||||||
Modify,
|
|
||||||
/// Retry after waiting (the error is temporary)
|
|
||||||
Wait,
|
|
||||||
}
|
|
||||||
impl IqErrorType {
|
|
||||||
pub fn as_str(&self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
IqErrorType::Auth => "auth",
|
|
||||||
IqErrorType::Cancel => "cancel",
|
|
||||||
IqErrorType::Continue => "continue",
|
|
||||||
IqErrorType::Modify => "modify",
|
|
||||||
IqErrorType::Wait => "wait",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ToXml for IqError {
|
|
||||||
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
|
||||||
let bytes = BytesStart::new(format!(r#"error xmlns="{}" type="{}""#, XMLNS, self.r#type.as_str()));
|
|
||||||
events.push(Event::Empty(bytes));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[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 +285,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 +310,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 +393,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 {
|
||||||
|
|
|
@ -2,8 +2,8 @@ use quick_xml::events::attributes::Attribute;
|
||||||
use quick_xml::events::{BytesEnd, BytesStart, Event};
|
use quick_xml::events::{BytesEnd, BytesStart, Event};
|
||||||
use quick_xml::name::{QName, ResolveResult};
|
use quick_xml::name::{QName, ResolveResult};
|
||||||
|
|
||||||
|
use anyhow::{Result, anyhow as ffail};
|
||||||
use crate::xml::*;
|
use crate::xml::*;
|
||||||
use anyhow::{anyhow as ffail, Result};
|
|
||||||
|
|
||||||
use super::bind::Jid;
|
use super::bind::Jid;
|
||||||
|
|
||||||
|
@ -174,7 +174,11 @@ impl FromXml for Identity {
|
||||||
let Some(r#type) = r#type else {
|
let Some(r#type) = r#type else {
|
||||||
return Err(ffail!("No type provided"));
|
return Err(ffail!("No type provided"));
|
||||||
};
|
};
|
||||||
let item = Identity { category, name, r#type };
|
let item = Identity {
|
||||||
|
category,
|
||||||
|
name,
|
||||||
|
r#type,
|
||||||
|
};
|
||||||
if end {
|
if end {
|
||||||
return Ok(item);
|
return Ok(item);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,16 +1,21 @@
|
||||||
#![feature(coroutines, coroutine_trait, type_alias_impl_trait, impl_trait_in_assoc_type)]
|
#![feature(
|
||||||
|
generators,
|
||||||
|
generator_trait,
|
||||||
|
type_alias_impl_trait,
|
||||||
|
impl_trait_in_assoc_type
|
||||||
|
)]
|
||||||
|
|
||||||
pub mod bind;
|
pub mod bind;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod disco;
|
pub mod disco;
|
||||||
pub mod muc;
|
pub mod muc;
|
||||||
mod prelude;
|
|
||||||
pub mod roster;
|
pub mod roster;
|
||||||
pub mod sasl;
|
pub mod sasl;
|
||||||
pub mod session;
|
pub mod session;
|
||||||
pub mod stanzaerror;
|
pub mod stanzaerror;
|
||||||
pub mod stream;
|
pub mod stream;
|
||||||
pub mod tls;
|
pub mod tls;
|
||||||
|
mod prelude;
|
||||||
pub mod xml;
|
pub mod xml;
|
||||||
|
|
||||||
// Implemented as a macro instead of a fn due to borrowck limitations
|
// Implemented as a macro instead of a fn due to borrowck limitations
|
||||||
|
|
|
@ -1,30 +1,47 @@
|
||||||
use quick_xml::events::{BytesStart, Event};
|
use quick_xml::events::{BytesStart, Event};
|
||||||
|
|
||||||
use crate::xml::*;
|
use crate::xml::*;
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow as ffail, Result};
|
||||||
use quick_xml::name::ResolveResult;
|
|
||||||
|
|
||||||
pub const XMLNS: &'static str = "jabber:iq:roster";
|
pub const XMLNS: &'static str = "jabber:iq:roster";
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Debug)]
|
#[derive(PartialEq, Eq, Debug)]
|
||||||
pub struct RosterQuery;
|
pub struct RosterQuery;
|
||||||
|
|
||||||
|
pub struct QueryParser(QueryParserInner);
|
||||||
|
|
||||||
|
enum QueryParserInner {
|
||||||
|
Initial,
|
||||||
|
InQuery,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parser for QueryParser {
|
||||||
|
type Output = Result<RosterQuery>;
|
||||||
|
|
||||||
|
fn consume<'a>(
|
||||||
|
self: Self,
|
||||||
|
namespace: quick_xml::name::ResolveResult,
|
||||||
|
event: &quick_xml::events::Event<'a>,
|
||||||
|
) -> Continuation<Self, Self::Output> {
|
||||||
|
match self.0 {
|
||||||
|
QueryParserInner::Initial => match event {
|
||||||
|
Event::Start(_) => Continuation::Continue(QueryParser(QueryParserInner::InQuery)),
|
||||||
|
Event::Empty(_) => Continuation::Final(Ok(RosterQuery)),
|
||||||
|
_ => Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}"))),
|
||||||
|
},
|
||||||
|
QueryParserInner::InQuery => match event {
|
||||||
|
Event::End(_) => Continuation::Final(Ok(RosterQuery)),
|
||||||
|
_ => Continuation::Final(Err(ffail!("Unexpected XML event: {event:?}"))),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FromXml for RosterQuery {
|
impl FromXml for RosterQuery {
|
||||||
type P = impl Parser<Output = Result<Self>>;
|
type P = QueryParser;
|
||||||
|
|
||||||
fn parse() -> Self::P {
|
fn parse() -> Self::P {
|
||||||
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|
QueryParser(QueryParserInner::Initial)
|
||||||
match event {
|
|
||||||
Event::Start(_) => (),
|
|
||||||
Event::Empty(_) => return Ok(RosterQuery),
|
|
||||||
_ => return Err(anyhow!("Unexpected XML event: {event:?}")),
|
|
||||||
}
|
|
||||||
(namespace, event) = yield;
|
|
||||||
match event {
|
|
||||||
Event::End(_) => return Ok(RosterQuery),
|
|
||||||
_ => return Err(anyhow!("Unexpected XML event: {event:?}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -35,6 +52,9 @@ impl FromXmlTag for RosterQuery {
|
||||||
|
|
||||||
impl ToXml for RosterQuery {
|
impl ToXml for RosterQuery {
|
||||||
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
||||||
events.push(Event::Empty(BytesStart::new(format!(r#"query xmlns="{}""#, XMLNS))));
|
events.push(Event::Empty(BytesStart::new(format!(
|
||||||
|
r#"query xmlns="{}""#,
|
||||||
|
XMLNS
|
||||||
|
))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,16 +1,17 @@
|
||||||
use std::borrow::Borrow;
|
use std::borrow::Borrow;
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use quick_xml::{
|
||||||
use quick_xml::events::{BytesStart, Event};
|
events::{BytesStart, Event},
|
||||||
use quick_xml::{NsReader, Writer};
|
NsReader, Writer,
|
||||||
|
};
|
||||||
use tokio::io::{AsyncBufRead, AsyncWrite};
|
use tokio::io::{AsyncBufRead, AsyncWrite};
|
||||||
|
|
||||||
use super::skip_text;
|
use super::skip_text;
|
||||||
|
use anyhow::{anyhow, Result};
|
||||||
|
|
||||||
pub enum Mechanism {
|
pub enum Mechanism {
|
||||||
Plain,
|
Plain,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Mechanism {
|
impl Mechanism {
|
||||||
pub fn to_str(&self) -> &'static str {
|
pub fn to_str(&self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
|
@ -30,9 +31,11 @@ pub struct Auth {
|
||||||
pub mechanism: Mechanism,
|
pub mechanism: Mechanism,
|
||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Auth {
|
impl Auth {
|
||||||
pub async fn parse(reader: &mut NsReader<impl AsyncBufRead + Unpin>, buf: &mut Vec<u8>) -> Result<Auth> {
|
pub async fn parse(
|
||||||
|
reader: &mut NsReader<impl AsyncBufRead + Unpin>,
|
||||||
|
buf: &mut Vec<u8>,
|
||||||
|
) -> Result<Auth> {
|
||||||
let event = skip_text!(reader, buf);
|
let event = skip_text!(reader, buf);
|
||||||
let mechanism = if let Event::Start(bytes) = event {
|
let mechanism = if let Event::Start(bytes) = event {
|
||||||
let mut mechanism = None;
|
let mut mechanism = None;
|
||||||
|
@ -66,7 +69,6 @@ impl Auth {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Success;
|
pub struct Success;
|
||||||
|
|
||||||
impl Success {
|
impl Success {
|
||||||
pub async fn write_xml(&self, writer: &mut Writer<impl AsyncWrite + Unpin>) -> Result<()> {
|
pub async fn write_xml(&self, writer: &mut Writer<impl AsyncWrite + Unpin>) -> Result<()> {
|
||||||
let event = BytesStart::new(r#"success xmlns="urn:ietf:params:xml:ns:xmpp-sasl""#);
|
let event = BytesStart::new(r#"success xmlns="urn:ietf:params:xml:ns:xmpp-sasl""#);
|
||||||
|
|
|
@ -2,29 +2,48 @@ use quick_xml::events::{BytesStart, Event};
|
||||||
|
|
||||||
use crate::xml::*;
|
use crate::xml::*;
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use quick_xml::name::ResolveResult;
|
|
||||||
|
|
||||||
pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-session";
|
pub const XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-session";
|
||||||
|
|
||||||
#[derive(PartialEq, Eq, Debug)]
|
#[derive(PartialEq, Eq, Debug)]
|
||||||
pub struct Session;
|
pub struct Session;
|
||||||
|
|
||||||
|
pub struct SessionParser(SessionParserInner);
|
||||||
|
|
||||||
|
enum SessionParserInner {
|
||||||
|
Initial,
|
||||||
|
InSession,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parser for SessionParser {
|
||||||
|
type Output = Result<Session>;
|
||||||
|
|
||||||
|
fn consume<'a>(
|
||||||
|
self: Self,
|
||||||
|
namespace: quick_xml::name::ResolveResult,
|
||||||
|
event: &quick_xml::events::Event<'a>,
|
||||||
|
) -> Continuation<Self, Self::Output> {
|
||||||
|
match self.0 {
|
||||||
|
SessionParserInner::Initial => match event {
|
||||||
|
Event::Start(_) => {
|
||||||
|
Continuation::Continue(SessionParser(SessionParserInner::InSession))
|
||||||
|
}
|
||||||
|
Event::Empty(_) => Continuation::Final(Ok(Session)),
|
||||||
|
_ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
|
||||||
|
},
|
||||||
|
SessionParserInner::InSession => match event {
|
||||||
|
Event::End(_) => Continuation::Final(Ok(Session)),
|
||||||
|
_ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FromXml for Session {
|
impl FromXml for Session {
|
||||||
type P = impl Parser<Output = Result<Self>>;
|
type P = SessionParser;
|
||||||
|
|
||||||
fn parse() -> Self::P {
|
fn parse() -> Self::P {
|
||||||
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|
SessionParser(SessionParserInner::Initial)
|
||||||
match event {
|
|
||||||
Event::Start(_) => (),
|
|
||||||
Event::Empty(_) => return Ok(Session),
|
|
||||||
_ => return Err(anyhow!("Unexpected XML event: {event:?}")),
|
|
||||||
}
|
|
||||||
(namespace, event) = yield;
|
|
||||||
match event {
|
|
||||||
Event::End(_) => return Ok(Session),
|
|
||||||
_ => return Err(anyhow!("Unexpected XML event: {event:?}")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -35,6 +54,9 @@ impl FromXmlTag for Session {
|
||||||
|
|
||||||
impl ToXml for Session {
|
impl ToXml for Session {
|
||||||
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
fn serialize(&self, events: &mut Vec<Event<'static>>) {
|
||||||
events.push(Event::Empty(BytesStart::new(format!(r#"session xmlns="{}""#, XMLNS))));
|
events.push(Event::Empty(BytesStart::new(format!(
|
||||||
|
r#"session xmlns="{}""#,
|
||||||
|
XMLNS
|
||||||
|
))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -6,8 +6,8 @@ use tokio::io::{AsyncBufRead, AsyncWrite};
|
||||||
|
|
||||||
use super::skip_text;
|
use super::skip_text;
|
||||||
|
|
||||||
use crate::xml::ToXml;
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
|
use crate::xml::ToXml;
|
||||||
|
|
||||||
pub static XMLNS: &'static str = "http://etherx.jabber.org/streams";
|
pub static XMLNS: &'static str = "http://etherx.jabber.org/streams";
|
||||||
pub static PREFIX: &'static str = "stream";
|
pub static PREFIX: &'static str = "stream";
|
||||||
|
@ -24,24 +24,14 @@ impl ClientStreamStart {
|
||||||
reader: &mut NsReader<impl AsyncBufRead + Unpin>,
|
reader: &mut NsReader<impl AsyncBufRead + Unpin>,
|
||||||
buf: &mut Vec<u8>,
|
buf: &mut Vec<u8>,
|
||||||
) -> Result<ClientStreamStart> {
|
) -> Result<ClientStreamStart> {
|
||||||
let mut incoming = skip_text!(reader, buf);
|
let incoming = skip_text!(reader, buf);
|
||||||
if let Event::Decl(bytes) = incoming {
|
|
||||||
// this is <?xml ...> header
|
|
||||||
if let Some(encoding) = bytes.encoding() {
|
|
||||||
let encoding = encoding?;
|
|
||||||
if &*encoding != b"UTF-8" {
|
|
||||||
return Err(anyhow!("Unsupported encoding: {encoding:?}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
incoming = skip_text!(reader, buf);
|
|
||||||
}
|
|
||||||
if let Event::Start(e) = incoming {
|
if let Event::Start(e) = incoming {
|
||||||
let (ns, local) = reader.resolve_element(e.name());
|
let (ns, local) = reader.resolve_element(e.name());
|
||||||
if ns != ResolveResult::Bound(Namespace(XMLNS.as_bytes())) {
|
if ns != ResolveResult::Bound(Namespace(XMLNS.as_bytes())) {
|
||||||
return Err(anyhow!("Invalid namespace for stream element"));
|
return Err(panic!());
|
||||||
}
|
}
|
||||||
if local.into_inner() != b"stream" {
|
if local.into_inner() != b"stream" {
|
||||||
return Err(anyhow!("Invalid local name for stream element"));
|
return Err(panic!());
|
||||||
}
|
}
|
||||||
let mut to = None;
|
let mut to = None;
|
||||||
let mut lang = None;
|
let mut lang = None;
|
||||||
|
@ -54,7 +44,10 @@ impl ClientStreamStart {
|
||||||
let value = attr.unescape_value()?;
|
let value = attr.unescape_value()?;
|
||||||
to = Some(value.to_string());
|
to = Some(value.to_string());
|
||||||
}
|
}
|
||||||
(ResolveResult::Bound(Namespace(b"http://www.w3.org/XML/1998/namespace")), b"lang") => {
|
(
|
||||||
|
ResolveResult::Bound(Namespace(b"http://www.w3.org/XML/1998/namespace")),
|
||||||
|
b"lang",
|
||||||
|
) => {
|
||||||
let value = attr.unescape_value()?;
|
let value = attr.unescape_value()?;
|
||||||
lang = Some(value.to_string());
|
lang = Some(value.to_string());
|
||||||
}
|
}
|
||||||
|
@ -71,7 +64,7 @@ impl ClientStreamStart {
|
||||||
version: version.unwrap(),
|
version: version.unwrap(),
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
Err(anyhow!("Incoming message does not belong XML Start Event"))
|
Err(panic!())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -131,15 +124,21 @@ pub struct Features {
|
||||||
}
|
}
|
||||||
impl Features {
|
impl Features {
|
||||||
pub async fn write_xml(&self, writer: &mut Writer<impl AsyncWrite + Unpin>) -> Result<()> {
|
pub async fn write_xml(&self, writer: &mut Writer<impl AsyncWrite + Unpin>) -> Result<()> {
|
||||||
writer.write_event_async(Event::Start(BytesStart::new("stream:features"))).await?;
|
writer
|
||||||
|
.write_event_async(Event::Start(BytesStart::new("stream:features")))
|
||||||
|
.await?;
|
||||||
if self.start_tls {
|
if self.start_tls {
|
||||||
writer
|
writer
|
||||||
.write_event_async(Event::Start(BytesStart::new(
|
.write_event_async(Event::Start(BytesStart::new(
|
||||||
r#"starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls""#,
|
r#"starttls xmlns="urn:ietf:params:xml:ns:xmpp-tls""#,
|
||||||
)))
|
)))
|
||||||
.await?;
|
.await?;
|
||||||
writer.write_event_async(Event::Empty(BytesStart::new("required"))).await?;
|
writer
|
||||||
writer.write_event_async(Event::End(BytesEnd::new("starttls"))).await?;
|
.write_event_async(Event::Empty(BytesStart::new("required")))
|
||||||
|
.await?;
|
||||||
|
writer
|
||||||
|
.write_event_async(Event::End(BytesEnd::new("starttls")))
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
if self.mechanisms {
|
if self.mechanisms {
|
||||||
writer
|
writer
|
||||||
|
@ -147,10 +146,18 @@ impl Features {
|
||||||
r#"mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl""#,
|
r#"mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl""#,
|
||||||
)))
|
)))
|
||||||
.await?;
|
.await?;
|
||||||
writer.write_event_async(Event::Start(BytesStart::new(r#"mechanism"#))).await?;
|
writer
|
||||||
writer.write_event_async(Event::Text(BytesText::new("PLAIN"))).await?;
|
.write_event_async(Event::Start(BytesStart::new(r#"mechanism"#)))
|
||||||
writer.write_event_async(Event::End(BytesEnd::new("mechanism"))).await?;
|
.await?;
|
||||||
writer.write_event_async(Event::End(BytesEnd::new("mechanisms"))).await?;
|
writer
|
||||||
|
.write_event_async(Event::Text(BytesText::new("PLAIN")))
|
||||||
|
.await?;
|
||||||
|
writer
|
||||||
|
.write_event_async(Event::End(BytesEnd::new("mechanism")))
|
||||||
|
.await?;
|
||||||
|
writer
|
||||||
|
.write_event_async(Event::End(BytesEnd::new("mechanisms")))
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
if self.bind {
|
if self.bind {
|
||||||
writer
|
writer
|
||||||
|
@ -159,7 +166,9 @@ impl Features {
|
||||||
)))
|
)))
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
writer.write_event_async(Event::End(BytesEnd::new("stream:features"))).await?;
|
writer
|
||||||
|
.write_event_async(Event::End(BytesEnd::new("stream:features")))
|
||||||
|
.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -173,7 +182,9 @@ mod test {
|
||||||
let input = r###"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="vlnv.dev" version="1.0" xmlns="jabber:client" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">"###;
|
let input = r###"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="vlnv.dev" version="1.0" xmlns="jabber:client" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace">"###;
|
||||||
let mut reader = NsReader::from_reader(input.as_bytes());
|
let mut reader = NsReader::from_reader(input.as_bytes());
|
||||||
let mut buf = vec![];
|
let mut buf = vec![];
|
||||||
let res = ClientStreamStart::parse(&mut reader, &mut buf).await.unwrap();
|
let res = ClientStreamStart::parse(&mut reader, &mut buf)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
res,
|
res,
|
||||||
ClientStreamStart {
|
ClientStreamStart {
|
||||||
|
|
|
@ -12,7 +12,10 @@ pub static XMLNS: &'static str = "urn:ietf:params:xml:ns:xmpp-tls";
|
||||||
|
|
||||||
pub struct StartTLS;
|
pub struct StartTLS;
|
||||||
impl StartTLS {
|
impl StartTLS {
|
||||||
pub async fn parse(reader: &mut NsReader<impl AsyncBufRead + Unpin>, buf: &mut Vec<u8>) -> Result<StartTLS> {
|
pub async fn parse(
|
||||||
|
reader: &mut NsReader<impl AsyncBufRead + Unpin>,
|
||||||
|
buf: &mut Vec<u8>,
|
||||||
|
) -> Result<StartTLS> {
|
||||||
let incoming = skip_text!(reader, buf);
|
let incoming = skip_text!(reader, buf);
|
||||||
if let Event::Empty(ref e) = incoming {
|
if let Event::Empty(ref e) = incoming {
|
||||||
if e.name().0 == b"starttls" {
|
if e.name().0 == b"starttls" {
|
||||||
|
|
|
@ -1,35 +1,59 @@
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use derive_more::From;
|
||||||
|
|
||||||
#[derive(Default, Debug, PartialEq, Eq)]
|
#[derive(Default, Debug, PartialEq, Eq)]
|
||||||
pub struct Ignore;
|
pub struct Ignore;
|
||||||
|
|
||||||
|
#[derive(From)]
|
||||||
|
pub struct IgnoreParser(IgnoreParserInner);
|
||||||
|
|
||||||
|
enum IgnoreParserInner {
|
||||||
|
Initial,
|
||||||
|
InTag { name: Vec<u8>, depth: u8 },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parser for IgnoreParser {
|
||||||
|
type Output = Result<Ignore>;
|
||||||
|
|
||||||
|
fn consume<'a>(
|
||||||
|
self: Self,
|
||||||
|
_: ResolveResult,
|
||||||
|
event: &Event<'a>,
|
||||||
|
) -> Continuation<Self, Self::Output> {
|
||||||
|
match self.0 {
|
||||||
|
IgnoreParserInner::Initial => match event {
|
||||||
|
Event::Start(bytes) => {
|
||||||
|
let name = bytes.name().0.to_owned();
|
||||||
|
Continuation::Continue(IgnoreParserInner::InTag { name, depth: 0 }.into())
|
||||||
|
}
|
||||||
|
Event::Empty(_) => Continuation::Final(Ok(Ignore)),
|
||||||
|
_ => Continuation::Final(Ok(Ignore)),
|
||||||
|
},
|
||||||
|
IgnoreParserInner::InTag { name, depth } => match event {
|
||||||
|
Event::End(bytes) if name == bytes.name().0 => {
|
||||||
|
if depth == 0 {
|
||||||
|
Continuation::Final(Ok(Ignore))
|
||||||
|
} else {
|
||||||
|
Continuation::Continue(
|
||||||
|
IgnoreParserInner::InTag {
|
||||||
|
name,
|
||||||
|
depth: depth - 1,
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Continuation::Continue(IgnoreParserInner::InTag { name, depth }.into()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl FromXml for Ignore {
|
impl FromXml for Ignore {
|
||||||
type P = impl Parser<Output = Result<Self>>;
|
type P = IgnoreParser;
|
||||||
|
|
||||||
fn parse() -> Self::P {
|
fn parse() -> Self::P {
|
||||||
|(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
|
IgnoreParserInner::Initial.into()
|
||||||
let mut depth = match event {
|
|
||||||
Event::Start(bytes) => 0,
|
|
||||||
Event::Empty(_) => return Ok(Ignore),
|
|
||||||
_ => return Ok(Ignore),
|
|
||||||
};
|
|
||||||
loop {
|
|
||||||
(namespace, event) = yield;
|
|
||||||
match event {
|
|
||||||
Event::End(_) => {
|
|
||||||
if depth == 0 {
|
|
||||||
return Ok(Ignore);
|
|
||||||
} else {
|
|
||||||
depth -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Event::Start(_) => {
|
|
||||||
depth += 1;
|
|
||||||
}
|
|
||||||
_ => (),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
use std::ops::Coroutine;
|
use std::ops::Generator;
|
||||||
use std::pin::Pin;
|
use std::pin::Pin;
|
||||||
|
|
||||||
|
use quick_xml::NsReader;
|
||||||
use quick_xml::events::Event;
|
use quick_xml::events::Event;
|
||||||
use quick_xml::name::ResolveResult;
|
use quick_xml::name::ResolveResult;
|
||||||
use quick_xml::NsReader;
|
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
|
@ -28,24 +28,33 @@ pub trait FromXmlTag: FromXml {
|
||||||
pub trait Parser: Sized {
|
pub trait Parser: Sized {
|
||||||
type Output;
|
type Output;
|
||||||
|
|
||||||
fn consume<'a>(self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output>;
|
fn consume<'a>(
|
||||||
|
self: Self,
|
||||||
|
namespace: ResolveResult,
|
||||||
|
event: &Event<'a>,
|
||||||
|
) -> Continuation<Self, Self::Output>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T, Out> Parser for T
|
impl<T, Out> Parser for T
|
||||||
where
|
where
|
||||||
T: Coroutine<(ResolveResult<'static>, &'static Event<'static>), Yield = (), Return = Out> + Unpin,
|
T: Generator<(ResolveResult<'static>, &'static Event<'static>), Yield = (), Return = Out>
|
||||||
|
+ Unpin,
|
||||||
{
|
{
|
||||||
type Output = Out;
|
type Output = Out;
|
||||||
|
|
||||||
fn consume<'a>(mut self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output> {
|
fn consume<'a>(
|
||||||
|
mut self: Self,
|
||||||
|
namespace: ResolveResult,
|
||||||
|
event: &Event<'a>,
|
||||||
|
) -> Continuation<Self, Self::Output> {
|
||||||
let s = Pin::new(&mut self);
|
let s = Pin::new(&mut self);
|
||||||
// this is a very rude workaround fixing the fact that rust coroutines
|
// this is a very rude workaround fixing the fact that rust generators
|
||||||
// 1. don't support higher-kinded lifetimes (i.e. no `impl for <'a> Coroutine<Event<'a>>)
|
// 1. don't support higher-kinded lifetimes (i.e. no `impl for <'a> Generator<Event<'a>>)
|
||||||
// 2. don't track borrows across yield points and lack thereof
|
// 2. don't track borrows across yield points and lack thereof
|
||||||
// implementors of Parser should manually check that inputs are not used across yields
|
// implementors of Parser should manually check that inputs are not used across yields
|
||||||
match s.resume(unsafe { std::mem::transmute((namespace, event)) }) {
|
match s.resume(unsafe { std::mem::transmute((namespace, event)) }) {
|
||||||
std::ops::CoroutineState::Yielded(()) => Continuation::Continue(self),
|
std::ops::GeneratorState::Yielded(()) => Continuation::Continue(self),
|
||||||
std::ops::CoroutineState::Complete(res) => Continuation::Final(res),
|
std::ops::GeneratorState::Complete(res) => Continuation::Final(res),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,46 +0,0 @@
|
||||||
## Dependency diagram of the project
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
graph TD;
|
|
||||||
lavina-->mgmt-api;
|
|
||||||
lavina-->projection-irc;
|
|
||||||
lavina-->projection-xmpp;
|
|
||||||
lavina-->lavina-core;
|
|
||||||
|
|
||||||
projection-irc-->proto-irc;
|
|
||||||
projection-irc-->lavina-core;
|
|
||||||
|
|
||||||
projection-xmpp-->proto-xmpp;
|
|
||||||
projection-xmpp-->lavina-core;
|
|
||||||
|
|
||||||
sim-irc-->proto-irc;
|
|
||||||
sim-irc-->mgmt-api;
|
|
||||||
|
|
||||||
sim-xmpp-->proto-xmpp;
|
|
||||||
sim-xmpp-->mgmt-api;
|
|
||||||
|
|
||||||
workspace-->lavina;
|
|
||||||
workspace-->sim-irc;
|
|
||||||
workspace-->sim-xmpp;
|
|
||||||
```
|
|
||||||
|
|
||||||
A few rules:
|
|
||||||
- Only projections should be direct deps of `lavina`, there is no need to depend on `proto-*` crates.
|
|
||||||
- On the other hand, projections should not be dependencies of `sim-*` crates.
|
|
||||||
- `lavina-core` does not depend on protocol-specific crates.
|
|
||||||
|
|
||||||
## Lavina
|
|
||||||
|
|
||||||
**lavina-core**. This crate implements the core functionality of the server not specific to public interfaces. It includes handling general persistence, message casts, in future room authorization and cross-node communication.
|
|
||||||
|
|
||||||
**lavina**. The application crate. It's used to link other crates together and build the final binary with support for all protocols.
|
|
||||||
|
|
||||||
**mgmt-api**. Model definitions for management API to be used both in the server and client implementations.
|
|
||||||
|
|
||||||
## IRC
|
|
||||||
|
|
||||||
**proto-irc**. Protocol definition for IRC, includes both server-side and client-side messages and both serialization and deserialization where needed.
|
|
||||||
|
|
||||||
**projection-irc**. Projection of lavina-core onto the IRC client-to-server protocol implementation.
|
|
||||||
|
|
||||||
**sim-irc**. Future implementation of IRC client simulator to be used in integration and load testing.
|
|
|
@ -1,8 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "sasl"
|
|
||||||
edition = "2021"
|
|
||||||
version.workspace = true
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow.workspace = true
|
|
||||||
base64.workspace = true
|
|
|
@ -1,103 +0,0 @@
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
use base64::engine::general_purpose;
|
|
||||||
use base64::Engine;
|
|
||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
|
||||||
pub struct AuthBody {
|
|
||||||
pub login: String,
|
|
||||||
pub password: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AuthBody {
|
|
||||||
pub fn from_str(input: &[u8]) -> Result<AuthBody> {
|
|
||||||
match general_purpose::STANDARD.decode(input) {
|
|
||||||
Ok(decoded_body) => {
|
|
||||||
match String::from_utf8(decoded_body) {
|
|
||||||
Ok(parsed_to_string) => {
|
|
||||||
let separated_words: Vec<&str> = parsed_to_string.split("\x00").collect::<Vec<_>>().clone();
|
|
||||||
if separated_words.len() == 3 {
|
|
||||||
// first segment ignored (might be needed in the future)
|
|
||||||
Ok(AuthBody {
|
|
||||||
login: separated_words[1].to_string(),
|
|
||||||
password: separated_words[2].to_string(),
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
return Err(anyhow!("Incorrect auth format"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => return Err(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(e) => return Err(e.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test {
|
|
||||||
use super::*;
|
|
||||||
#[test]
|
|
||||||
fn test_returning_auth_body() {
|
|
||||||
let orig = b"\x00login\x00pass";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {
|
|
||||||
login: "login".to_string(),
|
|
||||||
password: "pass".to_string(),
|
|
||||||
};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(expected, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_ignoring_first_segment() {
|
|
||||||
let orig = b"ignored\x00login\x00pass";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {
|
|
||||||
login: "login".to_string(),
|
|
||||||
password: "pass".to_string(),
|
|
||||||
};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(expected, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_returning_auth_body_with_empty_strings() {
|
|
||||||
let orig = b"\x00\x00";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {
|
|
||||||
login: "".to_string(),
|
|
||||||
password: "".to_string(),
|
|
||||||
};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes()).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(expected, result);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_fail_if_size_less_then_3() {
|
|
||||||
let orig = b"login\x00pass";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {
|
|
||||||
login: "login".to_string(),
|
|
||||||
password: "pass".to_string(),
|
|
||||||
};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes());
|
|
||||||
|
|
||||||
assert!(result.is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_fail_if_size_greater_then_3() {
|
|
||||||
let orig = b"first\x00login\x00pass\x00other";
|
|
||||||
let encoded = general_purpose::STANDARD.encode(orig);
|
|
||||||
let expected = AuthBody {
|
|
||||||
login: "login".to_string(),
|
|
||||||
password: "pass".to_string(),
|
|
||||||
};
|
|
||||||
let result = AuthBody::from_str(encoded.as_bytes());
|
|
||||||
|
|
||||||
assert!(result.is_err());
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -8,23 +8,35 @@ 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:
|
||||||
|
|
||||||
openssl x509 -in certs/xmpp.pem -text
|
openssl x509 -in certs/xmpp.pem -text
|
||||||
|
|
||||||
|
Make sure `xmpp.key` starts and ends with:
|
||||||
|
```
|
||||||
|
-----BEGIN RSA PRIVATE KEY-----
|
||||||
|
-----END RSA PRIVATE KEY-----
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
## Protocol Specs
|
## Protocol Specs
|
||||||
|
|
||||||
XMPP XSDs - [https://xmpp.org/schemas/index.shtml]
|
XMPP XSDs - [https://xmpp.org/schemas/index.shtml]
|
||||||
|
|
||||||
IRC modern spec - [https://modern.ircdocs.horse/]
|
IRC modern spec - [https://modern.ircdocs.horse/]
|
||||||
|
|
||||||
|
## Initializing DB with some users
|
||||||
|
|
||||||
|
sqlite3 db.sqlite < test/init_state.sql
|
||||||
|
|
||||||
|
Same test migration could be used for integration tests in the future.
|
||||||
|
|
||||||
## Using irssi
|
## Using irssi
|
||||||
|
|
||||||
irssi in a TUI-based IRC client.
|
irssi in a TUI-based IRC client.
|
||||||
|
|
|
@ -1,55 +0,0 @@
|
||||||
# Building & Running Lavina
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
A server instance must be supplied with a configuration file to start up. The path to configuration is specified with a required CLI argument `--config <path>`.
|
|
||||||
|
|
||||||
Example configuration:
|
|
||||||
```toml
|
|
||||||
[telemetry]
|
|
||||||
# address for management and telemetry API
|
|
||||||
# should be kept private
|
|
||||||
listen_on = "127.0.0.1:8080"
|
|
||||||
|
|
||||||
[irc]
|
|
||||||
listen_on = "127.0.0.1:6667"
|
|
||||||
server_name = "irc.localhost"
|
|
||||||
|
|
||||||
[xmpp]
|
|
||||||
listen_on = "127.0.0.1:5222"
|
|
||||||
cert = "./certs/xmpp.pem"
|
|
||||||
key = "./certs/xmpp.key"
|
|
||||||
hostname = "localhost"
|
|
||||||
|
|
||||||
[storage]
|
|
||||||
db_path = "db.sqlite"
|
|
||||||
```
|
|
||||||
|
|
||||||
## With Docker Compose
|
|
||||||
|
|
||||||
Example `docker-compose.yml` file:
|
|
||||||
```yaml
|
|
||||||
version: '3.0'
|
|
||||||
|
|
||||||
services:
|
|
||||||
lavina:
|
|
||||||
image: git.vilunov.me/lavina/lavina:0.0.1
|
|
||||||
volumes:
|
|
||||||
- './config/:/etc/lavina/'
|
|
||||||
- './data/:/var/lib/lavina/'
|
|
||||||
ports:
|
|
||||||
- '5222:5222' # xmpp
|
|
||||||
- '6667:6667' # irc non-tls
|
|
||||||
- '127.0.0.1:1380:8080' # management http (private)
|
|
||||||
```
|
|
||||||
|
|
||||||
## With Cargo
|
|
||||||
|
|
||||||
You can run it via cargo:
|
|
||||||
|
|
||||||
cargo run -- --config config.toml
|
|
||||||
|
|
||||||
Or you can build it and run manually:
|
|
||||||
|
|
||||||
cargo build --release
|
|
||||||
./target/release/lavina --config config.toml
|
|
|
@ -2,10 +2,6 @@
|
||||||
|
|
||||||
Multiprotocol chat server based on open protocols.
|
Multiprotocol chat server based on open protocols.
|
||||||
|
|
||||||
- [How to run Lavina locally](docs/running.md)
|
|
||||||
- [Architectural diagrams](docs/flow.md)
|
|
||||||
- [Project structure](crates/readme.md)
|
|
||||||
|
|
||||||
## Goals
|
## Goals
|
||||||
|
|
||||||
#### Support for multiple open protocols
|
#### Support for multiple open protocols
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
nightly-2024-04-19
|
nightly-2023-08-15
|
||||||
|
|
|
@ -1,2 +1 @@
|
||||||
max_width = 120
|
max_width = 120
|
||||||
chain_width = 120
|
|
||||||
|
|
19
src/http.rs
19
src/http.rs
|
@ -7,7 +7,6 @@ use hyper::body::Bytes;
|
||||||
use hyper::server::conn::http1;
|
use hyper::server::conn::http1;
|
||||||
use hyper::service::service_fn;
|
use hyper::service::service_fn;
|
||||||
use hyper::{Method, Request, Response, StatusCode};
|
use hyper::{Method, Request, Response, StatusCode};
|
||||||
use hyper_util::rt::TokioIo;
|
|
||||||
use prometheus::{Encoder, Registry as MetricsRegistry, TextEncoder};
|
use prometheus::{Encoder, Registry as MetricsRegistry, TextEncoder};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
|
@ -16,7 +15,6 @@ use lavina_core::prelude::*;
|
||||||
use lavina_core::repo::Storage;
|
use lavina_core::repo::Storage;
|
||||||
use lavina_core::room::RoomRegistry;
|
use lavina_core::room::RoomRegistry;
|
||||||
use lavina_core::terminator::Terminator;
|
use lavina_core::terminator::Terminator;
|
||||||
use lavina_core::LavinaCore;
|
|
||||||
|
|
||||||
use mgmt_api::*;
|
use mgmt_api::*;
|
||||||
|
|
||||||
|
@ -30,20 +28,20 @@ pub struct ServerConfig {
|
||||||
pub async fn launch(
|
pub async fn launch(
|
||||||
config: ServerConfig,
|
config: ServerConfig,
|
||||||
metrics: MetricsRegistry,
|
metrics: MetricsRegistry,
|
||||||
core: LavinaCore,
|
rooms: RoomRegistry,
|
||||||
storage: Storage,
|
storage: Storage,
|
||||||
) -> Result<Terminator> {
|
) -> Result<Terminator> {
|
||||||
log::info!("Starting the http service");
|
log::info!("Starting the http service");
|
||||||
let listener = TcpListener::bind(config.listen_on).await?;
|
let listener = TcpListener::bind(config.listen_on).await?;
|
||||||
log::debug!("Listener started");
|
log::debug!("Listener started");
|
||||||
let terminator = Terminator::spawn(|rx| main_loop(listener, metrics, core, storage, rx.map(|_| ())));
|
let terminator = Terminator::spawn(|rx| main_loop(listener, metrics, rooms, storage, rx.map(|_| ())));
|
||||||
Ok(terminator)
|
Ok(terminator)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn main_loop(
|
async fn main_loop(
|
||||||
listener: TcpListener,
|
listener: TcpListener,
|
||||||
metrics: MetricsRegistry,
|
metrics: MetricsRegistry,
|
||||||
core: LavinaCore,
|
rooms: RoomRegistry,
|
||||||
storage: Storage,
|
storage: Storage,
|
||||||
termination: impl Future<Output = ()>,
|
termination: impl Future<Output = ()>,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
@ -54,15 +52,14 @@ async fn main_loop(
|
||||||
_ = &mut termination => break,
|
_ = &mut termination => break,
|
||||||
result = listener.accept() => {
|
result = listener.accept() => {
|
||||||
let (stream, _) = result?;
|
let (stream, _) = result?;
|
||||||
let stream = TokioIo::new(stream);
|
|
||||||
let metrics = metrics.clone();
|
let metrics = metrics.clone();
|
||||||
let core = core.clone();
|
let rooms = rooms.clone();
|
||||||
let storage = storage.clone();
|
let storage = storage.clone();
|
||||||
tokio::task::spawn(async move {
|
tokio::task::spawn(async move {
|
||||||
let registry = metrics.clone();
|
let registry = metrics.clone();
|
||||||
let core = core.clone();
|
let rooms = rooms.clone();
|
||||||
let storage = storage.clone();
|
let storage = storage.clone();
|
||||||
let server = http1::Builder::new().serve_connection(stream, service_fn(move |r| route(registry.clone(), core.clone(), storage.clone(), r)));
|
let server = http1::Builder::new().serve_connection(stream, service_fn(move |r| route(registry.clone(), rooms.clone(), storage.clone(), r)));
|
||||||
if let Err(err) = server.await {
|
if let Err(err) = server.await {
|
||||||
tracing::error!("Error serving connection: {:?}", err);
|
tracing::error!("Error serving connection: {:?}", err);
|
||||||
}
|
}
|
||||||
|
@ -76,13 +73,13 @@ async fn main_loop(
|
||||||
|
|
||||||
async fn route(
|
async fn route(
|
||||||
registry: MetricsRegistry,
|
registry: MetricsRegistry,
|
||||||
core: LavinaCore,
|
rooms: RoomRegistry,
|
||||||
storage: Storage,
|
storage: Storage,
|
||||||
request: Request<hyper::body::Incoming>,
|
request: Request<hyper::body::Incoming>,
|
||||||
) -> HttpResult<Response<Full<Bytes>>> {
|
) -> HttpResult<Response<Full<Bytes>>> {
|
||||||
let res = match (request.method(), request.uri().path()) {
|
let res = match (request.method(), request.uri().path()) {
|
||||||
(&Method::GET, "/metrics") => endpoint_metrics(registry),
|
(&Method::GET, "/metrics") => endpoint_metrics(registry),
|
||||||
(&Method::GET, "/rooms") => endpoint_rooms(core.rooms).await,
|
(&Method::GET, "/rooms") => endpoint_rooms(rooms).await,
|
||||||
(&Method::POST, paths::CREATE_PLAYER) => endpoint_create_player(request, storage).await.or5xx(),
|
(&Method::POST, paths::CREATE_PLAYER) => endpoint_create_player(request, storage).await.or5xx(),
|
||||||
(&Method::POST, paths::SET_PASSWORD) => endpoint_set_password(request, storage).await.or5xx(),
|
(&Method::POST, paths::SET_PASSWORD) => endpoint_set_password(request, storage).await.or5xx(),
|
||||||
_ => not_found(),
|
_ => not_found(),
|
||||||
|
|
26
src/main.rs
26
src/main.rs
|
@ -9,9 +9,10 @@ use figment::{providers::Toml, Figment};
|
||||||
use prometheus::Registry as MetricsRegistry;
|
use prometheus::Registry as MetricsRegistry;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use lavina_core::player::PlayerRegistry;
|
||||||
use lavina_core::prelude::*;
|
use lavina_core::prelude::*;
|
||||||
use lavina_core::repo::Storage;
|
use lavina_core::repo::Storage;
|
||||||
use lavina_core::LavinaCore;
|
use lavina_core::room::RoomRegistry;
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Deserialize, Debug)]
|
||||||
struct ServerConfig {
|
struct ServerConfig {
|
||||||
|
@ -48,12 +49,20 @@ async fn main() -> Result<()> {
|
||||||
xmpp: xmpp_config,
|
xmpp: xmpp_config,
|
||||||
storage: storage_config,
|
storage: storage_config,
|
||||||
} = config;
|
} = config;
|
||||||
let metrics = MetricsRegistry::new();
|
let mut metrics = MetricsRegistry::new();
|
||||||
let storage = Storage::open(storage_config).await?;
|
let storage = Storage::open(storage_config).await?;
|
||||||
let core = LavinaCore::new(metrics.clone(), storage.clone()).await?;
|
let rooms = RoomRegistry::new(&mut metrics, storage.clone())?;
|
||||||
let telemetry_terminator = http::launch(telemetry_config, metrics.clone(), core.clone(), storage.clone()).await?;
|
let mut players = PlayerRegistry::empty(rooms.clone(), &mut metrics)?;
|
||||||
let irc = projection_irc::launch(irc_config, core.clone(), metrics.clone(), storage.clone()).await?;
|
let telemetry_terminator = http::launch(telemetry_config, metrics.clone(), rooms.clone(), storage.clone()).await?;
|
||||||
let xmpp = projection_xmpp::launch(xmpp_config, core.clone(), metrics.clone(), storage.clone()).await?;
|
let irc = projection_irc::launch(
|
||||||
|
irc_config,
|
||||||
|
players.clone(),
|
||||||
|
rooms.clone(),
|
||||||
|
metrics.clone(),
|
||||||
|
storage.clone(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
let xmpp = projection_xmpp::launch(xmpp_config, players.clone(), rooms.clone(), metrics.clone()).await?;
|
||||||
tracing::info!("Started");
|
tracing::info!("Started");
|
||||||
|
|
||||||
sleep.await;
|
sleep.await;
|
||||||
|
@ -62,7 +71,10 @@ async fn main() -> Result<()> {
|
||||||
xmpp.terminate().await?;
|
xmpp.terminate().await?;
|
||||||
irc.terminate().await?;
|
irc.terminate().await?;
|
||||||
telemetry_terminator.terminate().await?;
|
telemetry_terminator.terminate().await?;
|
||||||
core.shutdown().await?;
|
players.shutdown_all().await?;
|
||||||
|
drop(players);
|
||||||
|
drop(rooms);
|
||||||
|
storage.close().await?;
|
||||||
tracing::info!("Shutdown complete");
|
tracing::info!("Shutdown complete");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue