forked from lavina/lavina
Compare commits
3 Commits
Author | SHA1 | Date |
---|---|---|
Nikita Vilunov | 63024c7586 | |
Nikita Vilunov | de2d0b967c | |
Nikita Vilunov | b29fb68e8f |
|
@ -12,7 +12,7 @@ jobs:
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
uses: https://github.com/actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
command: fmt
|
command: fmt
|
||||||
args: "--check --all"
|
args: "--check -p mgmt-api -p lavina-core -p projection-irc -p projection-xmpp -p sasl"
|
||||||
- name: cargo check
|
- name: cargo check
|
||||||
uses: https://github.com/actions-rs/cargo@v1
|
uses: https://github.com/actions-rs/cargo@v1
|
||||||
with:
|
with:
|
||||||
|
|
|
@ -1,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
|
@ -18,8 +18,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"
|
||||||
|
@ -62,4 +62,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 }
|
||||||
|
|
|
@ -14,7 +14,10 @@ use std::{
|
||||||
|
|
||||||
use prometheus::{IntGauge, Registry as MetricsRegistry};
|
use prometheus::{IntGauge, Registry as MetricsRegistry};
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use tokio::sync::mpsc::{channel, Receiver, Sender};
|
use tokio::{
|
||||||
|
sync::mpsc::{channel, Receiver, Sender},
|
||||||
|
task::JoinHandle,
|
||||||
|
};
|
||||||
|
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
use crate::room::{RoomHandle, RoomId, RoomInfo, RoomRegistry};
|
use crate::room::{RoomHandle, RoomId, RoomInfo, RoomRegistry};
|
||||||
|
@ -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,9 +177,6 @@ pub enum ClientCommand {
|
||||||
new_topic: Str,
|
new_topic: Str,
|
||||||
promise: Promise<()>,
|
promise: Promise<()>,
|
||||||
},
|
},
|
||||||
GetRooms {
|
|
||||||
promise: Promise<Vec<RoomInfo>>,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum JoinResult {
|
pub enum JoinResult {
|
||||||
|
@ -239,7 +243,7 @@ impl PlayerRegistry {
|
||||||
pub async fn shutdown_all(&mut self) -> Result<()> {
|
pub async fn shutdown_all(&mut self) -> Result<()> {
|
||||||
let mut inner = self.0.write().unwrap();
|
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:?}")
|
||||||
|
@ -262,7 +266,7 @@ struct Player {
|
||||||
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,
|
||||||
}
|
}
|
||||||
|
@ -287,152 +291,124 @@ impl Player {
|
||||||
async fn main_loop(mut self) -> Self {
|
async fn main_loop(mut self) -> Self {
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
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.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 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;
|
|
||||||
}
|
|
||||||
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 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 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 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 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 {
|
||||||
|
|
|
@ -31,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 {
|
||||||
|
@ -160,13 +160,9 @@ impl RoomHandle {
|
||||||
}
|
}
|
||||||
|
|
||||||
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>,
|
||||||
/// 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,
|
||||||
|
@ -184,7 +180,9 @@ impl Room {
|
||||||
|
|
||||||
async fn send_message(&mut self, author_id: PlayerId, body: Str) -> Result<()> {
|
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(),
|
||||||
|
@ -195,10 +193,6 @@ impl Room {
|
||||||
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 {
|
||||||
|
|
|
@ -1,10 +1,12 @@
|
||||||
use crate::prelude::*;
|
use crate::prelude::*;
|
||||||
|
|
||||||
|
/// A handle to a task that can be gracefully terminated.
|
||||||
pub struct Terminator {
|
pub struct Terminator {
|
||||||
signal: Promise<()>,
|
signal: Promise<()>,
|
||||||
completion: JoinHandle<Result<()>>,
|
completion: JoinHandle<Result<()>>,
|
||||||
}
|
}
|
||||||
impl Terminator {
|
impl Terminator {
|
||||||
|
/// Send a signal to the task to terminate and await its completion.
|
||||||
pub async fn terminate(self) -> Result<()> {
|
pub async fn terminate(self) -> Result<()> {
|
||||||
match self.signal.send(()) {
|
match self.signal.send(()) {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
|
@ -14,7 +16,10 @@ impl Terminator {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Used to spawn managed tasks with support for graceful shutdown
|
/// Spawn a task with support for graceful shutdown.
|
||||||
|
///
|
||||||
|
/// The launched task must listen for the termination signal and stop gracefully on receiving it.
|
||||||
|
/// The signal is sent by calling the `terminate` method on the returned `Terminator` instance outside the task.
|
||||||
pub fn spawn<Fun, Fut>(launcher: Fun) -> Terminator
|
pub fn spawn<Fun, Fut>(launcher: Fun) -> Terminator
|
||||||
where
|
where
|
||||||
Fun: FnOnce(Deferred<()>) -> Fut,
|
Fun: FnOnce(Deferred<()>) -> Fut,
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
max_width = 120
|
||||||
|
chain_width = 120
|
|
@ -30,8 +30,6 @@ mod cap;
|
||||||
|
|
||||||
use crate::cap::Capabilities;
|
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 {
|
||||||
pub listen_on: SocketAddr,
|
pub listen_on: SocketAddr,
|
||||||
|
@ -44,7 +42,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,
|
||||||
|
@ -64,24 +62,19 @@ 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);
|
let registered_user: Result<RegisteredUser> =
|
||||||
select! {
|
handle_registration(&mut reader, &mut writer, &mut storage, &config).await;
|
||||||
biased;
|
|
||||||
_ = &mut termination =>{
|
match registered_user {
|
||||||
log::info!("Socket handling was terminated");
|
Ok(user) => {
|
||||||
return Ok(())
|
log::debug!("User registered");
|
||||||
},
|
handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user).await?;
|
||||||
registered_user = handle_registration(&mut reader, &mut writer, &mut storage, &config) =>
|
}
|
||||||
match registered_user {
|
Err(err) => {
|
||||||
Ok(user) => {
|
log::debug!("Registration failed: {err}");
|
||||||
log::debug!("User registered");
|
}
|
||||||
handle_registered_socket(config, players, rooms, &mut reader, &mut writer, user).await?;
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
log::debug!("Registration failed: {err}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stream.shutdown().await?;
|
stream.shutdown().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -187,16 +180,14 @@ async fn handle_registration<'a>(
|
||||||
writer.flush().await?;
|
writer.flush().await?;
|
||||||
}
|
}
|
||||||
CapabilitySubcommand::End => {
|
CapabilitySubcommand::End => {
|
||||||
let Some((ref username, ref realname)) = future_username else {
|
let Some((username, realname)) = future_username else {
|
||||||
todo!();
|
todo!()
|
||||||
};
|
};
|
||||||
let Some(nickname) = future_nickname.clone() else {
|
let Some(nickname) = future_nickname.clone() else {
|
||||||
todo!();
|
todo!()
|
||||||
};
|
};
|
||||||
let username = username.clone();
|
|
||||||
let realname = realname.clone();
|
|
||||||
let candidate_user = RegisteredUser {
|
let candidate_user = RegisteredUser {
|
||||||
nickname: nickname.clone(),
|
nickname,
|
||||||
username,
|
username,
|
||||||
realname,
|
realname,
|
||||||
};
|
};
|
||||||
|
@ -206,15 +197,7 @@ async fn handle_registration<'a>(
|
||||||
break Ok(candidate_user);
|
break Ok(candidate_user);
|
||||||
} else {
|
} else {
|
||||||
let Some(candidate_password) = pass else {
|
let Some(candidate_password) = pass else {
|
||||||
sasl_fail_message(
|
todo!();
|
||||||
config.server_name.clone(),
|
|
||||||
nickname.clone(),
|
|
||||||
"User credentials was not provided".into(),
|
|
||||||
)
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
break Ok(candidate_user);
|
break Ok(candidate_user);
|
||||||
|
@ -226,20 +209,12 @@ async fn handle_registration<'a>(
|
||||||
future_nickname = Some(nickname);
|
future_nickname = Some(nickname);
|
||||||
} else if let Some((username, realname)) = future_username.clone() {
|
} else if let Some((username, realname)) = future_username.clone() {
|
||||||
let candidate_user = RegisteredUser {
|
let candidate_user = RegisteredUser {
|
||||||
nickname: nickname.clone(),
|
nickname,
|
||||||
username,
|
username,
|
||||||
realname,
|
realname,
|
||||||
};
|
};
|
||||||
let Some(candidate_password) = pass else {
|
let Some(candidate_password) = pass else {
|
||||||
sasl_fail_message(
|
todo!();
|
||||||
config.server_name.clone(),
|
|
||||||
nickname.clone(),
|
|
||||||
"User credentials was not provided".into(),
|
|
||||||
)
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
break Ok(candidate_user);
|
break Ok(candidate_user);
|
||||||
|
@ -252,20 +227,12 @@ async fn handle_registration<'a>(
|
||||||
future_username = Some((username, realname));
|
future_username = Some((username, realname));
|
||||||
} else if let Some(nickname) = future_nickname.clone() {
|
} else if let Some(nickname) = future_nickname.clone() {
|
||||||
let candidate_user = RegisteredUser {
|
let candidate_user = RegisteredUser {
|
||||||
nickname: nickname.clone(),
|
nickname,
|
||||||
username,
|
username,
|
||||||
realname,
|
realname,
|
||||||
};
|
};
|
||||||
let Some(candidate_password) = pass else {
|
let Some(candidate_password) = pass else {
|
||||||
sasl_fail_message(
|
todo!();
|
||||||
config.server_name.clone(),
|
|
||||||
nickname.clone(),
|
|
||||||
"User credentials was not provided".into(),
|
|
||||||
)
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
auth_user(storage, &*candidate_user.nickname, &*candidate_password).await?;
|
||||||
break Ok(candidate_user);
|
break Ok(candidate_user);
|
||||||
|
@ -288,59 +255,38 @@ async fn handle_registration<'a>(
|
||||||
.await?;
|
.await?;
|
||||||
writer.flush().await?;
|
writer.flush().await?;
|
||||||
} else {
|
} else {
|
||||||
if let Some(nickname) = future_nickname.clone() {
|
// TODO respond with 904
|
||||||
sasl_fail_message(
|
todo!();
|
||||||
config.server_name.clone(),
|
|
||||||
nickname.clone(),
|
|
||||||
"Unsupported mechanism".into(),
|
|
||||||
)
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
} else {
|
|
||||||
break Err(anyhow::Error::msg("Wrong authentication sequence"));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let body = AuthBody::from_str(body.as_bytes())?;
|
let body = AuthBody::from_str(body.as_bytes())?;
|
||||||
if let Err(e) = auth_user(storage, &body.login, &body.password).await {
|
auth_user(storage, &body.login, &body.password).await?;
|
||||||
tracing::warn!("Authentication failed: {:?}", e);
|
let login: Str = body.login.into();
|
||||||
if let Some(nickname) = future_nickname.clone() {
|
validated_user = Some(login.clone());
|
||||||
sasl_fail_message(config.server_name.clone(), nickname.clone(), "Bad credentials".into())
|
ServerMessage {
|
||||||
.write_async(writer)
|
tags: vec![],
|
||||||
.await?;
|
sender: Some(config.server_name.clone().into()),
|
||||||
writer.flush().await?;
|
body: ServerMessageBody::N900LoggedIn {
|
||||||
} else {
|
nick: login.clone(),
|
||||||
}
|
address: login.clone(),
|
||||||
} else {
|
account: login.clone(),
|
||||||
let login: Str = body.login.into();
|
message: format!("You are now logged in as {}", login).into(),
|
||||||
validated_user = Some(login.clone());
|
},
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::N900LoggedIn {
|
|
||||||
nick: login.clone(),
|
|
||||||
address: login.clone(),
|
|
||||||
account: login.clone(),
|
|
||||||
message: format!("You are now logged in as {}", login).into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(config.server_name.clone().into()),
|
|
||||||
body: ServerMessageBody::N903SaslSuccess {
|
|
||||||
nick: login.clone(),
|
|
||||||
message: "SASL authentication successful".into(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
.write_async(writer)
|
|
||||||
.await?;
|
|
||||||
writer.flush().await?;
|
|
||||||
}
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
ServerMessage {
|
||||||
|
tags: vec![],
|
||||||
|
sender: Some(config.server_name.clone().into()),
|
||||||
|
body: ServerMessageBody::N903SaslSuccess {
|
||||||
|
nick: login.clone(),
|
||||||
|
message: "SASL authentication successful".into(),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
.write_async(writer)
|
||||||
|
.await?;
|
||||||
|
writer.flush().await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO handle abortion of authentication
|
// TODO handle abortion of authentication
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
|
@ -351,14 +297,6 @@ async fn handle_registration<'a>(
|
||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sasl_fail_message(sender: Str, nick: Str, text: Str) -> ServerMessage {
|
|
||||||
ServerMessage {
|
|
||||||
tags: vec![],
|
|
||||||
sender: Some(sender),
|
|
||||||
body: ServerMessageBody::N904SaslFail { nick, text },
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn auth_user(storage: &mut Storage, login: &str, plain_password: &str) -> Result<()> {
|
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 = storage.retrieve_user_by_name(login).await?;
|
||||||
|
|
||||||
|
@ -393,14 +331,13 @@ async fn handle_registered_socket<'a>(
|
||||||
|
|
||||||
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.clone()).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)
|
||||||
|
@ -410,7 +347,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)
|
||||||
|
@ -420,7 +357,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)
|
||||||
|
@ -431,7 +368,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)
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
use std::io::ErrorKind;
|
|
||||||
use std::net::SocketAddr;
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
|
@ -10,8 +8,8 @@ use tokio::net::TcpStream;
|
||||||
|
|
||||||
use lavina_core::repo::{Storage, StorageConfig};
|
use lavina_core::repo::{Storage, StorageConfig};
|
||||||
use lavina_core::{player::PlayerRegistry, room::RoomRegistry};
|
use lavina_core::{player::PlayerRegistry, room::RoomRegistry};
|
||||||
use projection_irc::APP_VERSION;
|
|
||||||
use projection_irc::{launch, read_irc_message, RunningServer, ServerConfig};
|
use projection_irc::{launch, read_irc_message, RunningServer, ServerConfig};
|
||||||
|
|
||||||
struct TestScope<'a> {
|
struct TestScope<'a> {
|
||||||
reader: BufReader<ReadHalf<'a>>,
|
reader: BufReader<ReadHalf<'a>>,
|
||||||
writer: WriteHalf<'a>,
|
writer: WriteHalf<'a>,
|
||||||
|
@ -113,17 +111,10 @@ async fn scenario_basic() -> Result<()> {
|
||||||
s.send("PASS password").await?;
|
s.send("PASS password").await?;
|
||||||
s.send("NICK tester").await?;
|
s.send("NICK tester").await?;
|
||||||
s.send("USER UserName 0 * :Real Name").await?;
|
s.send("USER UserName 0 * :Real Name").await?;
|
||||||
s.expect(":testserver 001 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 002 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 003 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(
|
s.expect(":testserver 004 tester testserver kek-0.1.alpha.3 r CFILPQbcefgijklmnopqrstvz").await?;
|
||||||
format!(
|
|
||||||
":testserver 004 tester testserver {} r CFILPQbcefgijklmnopqrstvz",
|
|
||||||
&APP_VERSION
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
||||||
s.expect_nothing().await?;
|
s.expect_nothing().await?;
|
||||||
s.send("QUIT :Leaving").await?;
|
s.send("QUIT :Leaving").await?;
|
||||||
|
@ -168,17 +159,10 @@ async fn scenario_cap_full_negotiation() -> Result<()> {
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
s.send("CAP END").await?;
|
||||||
|
|
||||||
s.expect(":testserver 001 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 002 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 003 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(
|
s.expect(":testserver 004 tester testserver kek-0.1.alpha.3 r CFILPQbcefgijklmnopqrstvz").await?;
|
||||||
format!(
|
|
||||||
":testserver 004 tester testserver {} r CFILPQbcefgijklmnopqrstvz",
|
|
||||||
&APP_VERSION
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
||||||
s.expect_nothing().await?;
|
s.expect_nothing().await?;
|
||||||
s.send("QUIT :Leaving").await?;
|
s.send("QUIT :Leaving").await?;
|
||||||
|
@ -217,17 +201,10 @@ async fn scenario_cap_short_negotiation() -> Result<()> {
|
||||||
|
|
||||||
s.send("CAP END").await?;
|
s.send("CAP END").await?;
|
||||||
|
|
||||||
s.expect(":testserver 001 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 001 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 002 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 002 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(":testserver 003 tester :Welcome to testserver Server").await?;
|
s.expect(":testserver 003 tester :Welcome to Kek Server").await?;
|
||||||
s.expect(
|
s.expect(":testserver 004 tester testserver kek-0.1.alpha.3 r CFILPQbcefgijklmnopqrstvz").await?;
|
||||||
format!(
|
|
||||||
":testserver 004 tester testserver {} r CFILPQbcefgijklmnopqrstvz",
|
|
||||||
&APP_VERSION
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
||||||
s.expect_nothing().await?;
|
s.expect_nothing().await?;
|
||||||
s.send("QUIT :Leaving").await?;
|
s.send("QUIT :Leaving").await?;
|
||||||
|
@ -241,84 +218,3 @@ async fn scenario_cap_short_negotiation() -> Result<()> {
|
||||||
server.server.terminate().await?;
|
server.server.terminate().await?;
|
||||||
Ok(())
|
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(":testserver 001 tester :Welcome to testserver Server").await?;
|
|
||||||
s.expect(":testserver 002 tester :Welcome to testserver Server").await?;
|
|
||||||
s.expect(":testserver 003 tester :Welcome to testserver Server").await?;
|
|
||||||
s.expect(
|
|
||||||
format!(
|
|
||||||
":testserver 004 tester testserver {} r CFILPQbcefgijklmnopqrstvz",
|
|
||||||
&APP_VERSION
|
|
||||||
)
|
|
||||||
.as_str(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
s.expect(":testserver 005 tester CHANTYPES=# :are supported by this server").await?;
|
|
||||||
s.expect_nothing().await?;
|
|
||||||
s.send("QUIT :Leaving").await?;
|
|
||||||
s.expect(":testserver ERROR :Leaving the server").await?;
|
|
||||||
s.expect_eof().await?;
|
|
||||||
|
|
||||||
stream.shutdown().await?;
|
|
||||||
|
|
||||||
// wrap up
|
|
||||||
|
|
||||||
server.server.terminate().await?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn terminate_socket_scenario() -> Result<()> {
|
|
||||||
let mut server = TestServer::start().await?;
|
|
||||||
let address: SocketAddr = ("127.0.0.1:0".parse().unwrap());
|
|
||||||
|
|
||||||
// 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(())
|
|
||||||
}
|
|
||||||
|
|
|
@ -0,0 +1,2 @@
|
||||||
|
max_width = 120
|
||||||
|
chain_width = 120
|
|
@ -187,33 +187,18 @@ async fn handle_socket(
|
||||||
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(b);
|
let mut xml_writer = Writer::new(b);
|
||||||
|
|
||||||
pin!(termination);
|
let authenticated = socket_auth(&mut xml_reader, &mut xml_writer, &mut reader_buf, &mut storage).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) => {
|
&authenticated,
|
||||||
match authenticated {
|
&mut connection,
|
||||||
Ok(authenticated) => {
|
&rooms,
|
||||||
let mut connection = players.connect_to_player(authenticated.player_id.clone()).await;
|
)
|
||||||
socket_final(
|
.await?;
|
||||||
&mut xml_reader,
|
|
||||||
&mut xml_writer,
|
|
||||||
&mut reader_buf,
|
|
||||||
&authenticated,
|
|
||||||
&mut connection,
|
|
||||||
&rooms,
|
|
||||||
)
|
|
||||||
.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();
|
let b = xml_writer.into_inner();
|
||||||
|
|
|
@ -1,5 +1,3 @@
|
||||||
use std::io::ErrorKind;
|
|
||||||
use std::net::SocketAddr;
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
@ -8,7 +6,7 @@ use assert_matches::*;
|
||||||
use prometheus::Registry as MetricsRegistry;
|
use prometheus::Registry as MetricsRegistry;
|
||||||
use quick_xml::events::Event;
|
use quick_xml::events::Event;
|
||||||
use quick_xml::NsReader;
|
use quick_xml::NsReader;
|
||||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||||
use tokio::io::{ReadHalf as GenericReadHalf, WriteHalf as GenericWriteHalf};
|
use tokio::io::{ReadHalf as GenericReadHalf, WriteHalf as GenericWriteHalf};
|
||||||
use tokio::net::tcp::{ReadHalf, WriteHalf};
|
use tokio::net::tcp::{ReadHalf, WriteHalf};
|
||||||
use tokio::net::TcpStream;
|
use tokio::net::TcpStream;
|
||||||
|
@ -124,7 +122,7 @@ impl ServerCertVerifier for IgnoreCertVerification {
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn scenario_basic() -> Result<()> {
|
async fn scenario_basic() -> Result<()> {
|
||||||
tracing_subscriber::fmt::try_init();
|
tracing_subscriber::fmt::init();
|
||||||
let config = ServerConfig {
|
let config = ServerConfig {
|
||||||
listen_on: "127.0.0.1:0".parse().unwrap(),
|
listen_on: "127.0.0.1:0".parse().unwrap(),
|
||||||
cert: "tests/certs/xmpp.pem".parse().unwrap(),
|
cert: "tests/certs/xmpp.pem".parse().unwrap(),
|
||||||
|
@ -186,61 +184,3 @@ async fn scenario_basic() -> Result<()> {
|
||||||
server.terminate().await?;
|
server.terminate().await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn terminate_socket() -> Result<()> {
|
|
||||||
tracing_subscriber::fmt::try_init();
|
|
||||||
let config = ServerConfig {
|
|
||||||
listen_on: "127.0.0.1:0".parse().unwrap(),
|
|
||||||
cert: "tests/certs/xmpp.pem".parse().unwrap(),
|
|
||||||
key: "tests/certs/xmpp.key".parse().unwrap(),
|
|
||||||
};
|
|
||||||
let mut metrics = MetricsRegistry::new();
|
|
||||||
let mut storage = Storage::open(StorageConfig {
|
|
||||||
db_path: ":memory:".into(),
|
|
||||||
})
|
|
||||||
.await?;
|
|
||||||
let rooms = RoomRegistry::new(&mut metrics, storage.clone()).unwrap();
|
|
||||||
let players = PlayerRegistry::empty(rooms.clone(), &mut metrics).unwrap();
|
|
||||||
let server = launch(config, players, rooms, metrics, storage.clone()).await.unwrap();
|
|
||||||
let address: SocketAddr = ("127.0.0.1:0".parse().unwrap());
|
|
||||||
// test scenario
|
|
||||||
|
|
||||||
storage.create_user("tester").await?;
|
|
||||||
storage.set_password("tester", "password").await?;
|
|
||||||
|
|
||||||
let mut stream = TcpStream::connect(server.addr).await?;
|
|
||||||
let mut s = TestScope::new(&mut stream);
|
|
||||||
tracing::info!("TCP connection established");
|
|
||||||
|
|
||||||
s.send(r#"<?xml version="1.0"?>"#).await?;
|
|
||||||
|
|
||||||
s.send(r#"<stream:stream xmlns:stream="http://etherx.jabber.org/streams" to="127.0.0.1" xml:lang="en" xmlns:xml="http://www.w3.org/XML/1998/namespace" xmlns="jabber:client" version="1.0">"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Decl(_) => {});
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"stream"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Start(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"required"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"starttls"));
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::End(b) => assert_eq!(b.local_name().into_inner(), b"features"));
|
|
||||||
s.send(r#"<starttls/>"#).await?;
|
|
||||||
assert_matches!(s.next_xml_event().await?, Event::Empty(b) => assert_eq!(b.local_name().into_inner(), b"proceed"));
|
|
||||||
let buffer = s.buffer;
|
|
||||||
|
|
||||||
let connector = TlsConnector::from(Arc::new(
|
|
||||||
ClientConfig::builder()
|
|
||||||
.with_safe_defaults()
|
|
||||||
.with_custom_certificate_verifier(Arc::new(IgnoreCertVerification))
|
|
||||||
.with_no_client_auth(),
|
|
||||||
));
|
|
||||||
|
|
||||||
tracing::info!("Initiating TLS connection...");
|
|
||||||
let mut stream = connector.connect(ServerName::IpAddress(server.addr.ip()), stream).await?;
|
|
||||||
tracing::info!("TLS connection established");
|
|
||||||
|
|
||||||
server.terminate().await?;
|
|
||||||
|
|
||||||
assert_eq!(stream.read_u8().await.unwrap_err().kind(), ErrorKind::UnexpectedEof);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
|
@ -7,42 +7,42 @@ 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,
|
||||||
|
@ -51,12 +51,12 @@ pub enum ClientMessage {
|
||||||
chan: Chan,
|
chan: Chan,
|
||||||
message: 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,
|
||||||
},
|
},
|
||||||
|
|
|
@ -30,15 +30,11 @@ 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 {
|
||||||
|
@ -118,7 +114,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 +130,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 +146,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;
|
||||||
|
@ -154,11 +152,7 @@ pub enum ServerMessageBody {
|
||||||
N903SaslSuccess {
|
N903SaslSuccess {
|
||||||
nick: Str,
|
nick: Str,
|
||||||
message: Str,
|
message: Str,
|
||||||
},
|
}
|
||||||
N904SaslFail {
|
|
||||||
nick: Str,
|
|
||||||
text: Str,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ServerMessageBody {
|
impl ServerMessageBody {
|
||||||
|
@ -273,7 +267,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,14 +309,20 @@ 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 {
|
for member in members {
|
||||||
writer.write_all(member.prefix.to_string().as_bytes()).await?;
|
writer
|
||||||
|
.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?;
|
||||||
writer.write_all(b" ").await?;
|
writer.write_all(b" ").await?;
|
||||||
}
|
}
|
||||||
|
@ -330,7 +334,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?;
|
||||||
|
@ -345,12 +353,7 @@ 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 {
|
ServerMessageBody::N900LoggedIn { nick, address, account, message } => {
|
||||||
nick,
|
|
||||||
address,
|
|
||||||
account,
|
|
||||||
message,
|
|
||||||
} => {
|
|
||||||
writer.write_all(b"900 ").await?;
|
writer.write_all(b"900 ").await?;
|
||||||
writer.write_all(nick.as_bytes()).await?;
|
writer.write_all(nick.as_bytes()).await?;
|
||||||
writer.write_all(b" ").await?;
|
writer.write_all(b" ").await?;
|
||||||
|
@ -366,13 +369,6 @@ 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::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(())
|
||||||
}
|
}
|
||||||
|
|
|
@ -42,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-Z]+)@)?([a-zA-Z.]+)(/([a-zA-Z\-]+))?$").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,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -129,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")),
|
||||||
|
@ -146,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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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(
|
||||||
|
coroutines,
|
||||||
|
coroutine_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
|
||||||
|
|
|
@ -52,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
|
||||||
|
))));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,7 +25,9 @@ impl Parser for SessionParser {
|
||||||
) -> Continuation<Self, Self::Output> {
|
) -> Continuation<Self, Self::Output> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
SessionParserInner::Initial => match event {
|
SessionParserInner::Initial => match event {
|
||||||
Event::Start(_) => Continuation::Continue(SessionParser(SessionParserInner::InSession)),
|
Event::Start(_) => {
|
||||||
|
Continuation::Continue(SessionParser(SessionParserInner::InSession))
|
||||||
|
}
|
||||||
Event::Empty(_) => Continuation::Final(Ok(Session)),
|
Event::Empty(_) => Continuation::Final(Ok(Session)),
|
||||||
_ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
|
_ => Continuation::Final(Err(anyhow!("Unexpected XML event: {event:?}"))),
|
||||||
},
|
},
|
||||||
|
@ -52,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";
|
||||||
|
@ -44,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());
|
||||||
}
|
}
|
||||||
|
@ -121,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
|
||||||
|
@ -137,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
|
||||||
|
@ -149,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(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -163,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" {
|
||||||
|
|
|
@ -15,7 +15,11 @@ enum IgnoreParserInner {
|
||||||
impl Parser for IgnoreParser {
|
impl Parser for IgnoreParser {
|
||||||
type Output = Result<Ignore>;
|
type Output = Result<Ignore>;
|
||||||
|
|
||||||
fn consume<'a>(self: Self, _: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output> {
|
fn consume<'a>(
|
||||||
|
self: Self,
|
||||||
|
_: ResolveResult,
|
||||||
|
event: &Event<'a>,
|
||||||
|
) -> Continuation<Self, Self::Output> {
|
||||||
match self.0 {
|
match self.0 {
|
||||||
IgnoreParserInner::Initial => match event {
|
IgnoreParserInner::Initial => match event {
|
||||||
Event::Start(bytes) => {
|
Event::Start(bytes) => {
|
||||||
|
@ -30,7 +34,13 @@ impl Parser for IgnoreParser {
|
||||||
if depth == 0 {
|
if depth == 0 {
|
||||||
Continuation::Final(Ok(Ignore))
|
Continuation::Final(Ok(Ignore))
|
||||||
} else {
|
} else {
|
||||||
Continuation::Continue(IgnoreParserInner::InTag { name, depth: depth - 1 }.into())
|
Continuation::Continue(
|
||||||
|
IgnoreParserInner::InTag {
|
||||||
|
name,
|
||||||
|
depth: depth - 1,
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
_ => Continuation::Continue(IgnoreParserInner::InTag { name, depth }.into()),
|
_ => Continuation::Continue(IgnoreParserInner::InTag { name, depth }.into()),
|
||||||
|
|
|
@ -1,9 +1,9 @@
|
||||||
use std::ops::Coroutine;
|
use std::ops::Coroutine;
|
||||||
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,16 +28,25 @@ 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: Coroutine<(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 coroutines
|
||||||
// 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> Coroutine<Event<'a>>)
|
||||||
|
|
|
@ -2,9 +2,9 @@
|
||||||
|
|
||||||
Multiprotocol chat server based on open protocols.
|
Multiprotocol chat server based on open protocols.
|
||||||
|
|
||||||
- [How to run Lavina locally](docs/running.md)
|
- [How to run Lavina locally](/docs/running.md)
|
||||||
- [Architectural diagrams](docs/flow.md)
|
- [Architectural diagrams](/docs/flow.md)
|
||||||
- [Project structure](crates/readme.md)
|
- [Project structure](crates)
|
||||||
|
|
||||||
## Goals
|
## Goals
|
||||||
|
|
||||||
|
|
|
@ -1 +1 @@
|
||||||
nightly-2024-03-20
|
nightly-2023-12-07
|
||||||
|
|
|
@ -1,2 +1 @@
|
||||||
max_width = 120
|
max_width = 120
|
||||||
chain_width = 120
|
|
|
@ -62,14 +62,7 @@ async fn main() -> Result<()> {
|
||||||
storage.clone(),
|
storage.clone(),
|
||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
let xmpp = projection_xmpp::launch(
|
let xmpp = projection_xmpp::launch(xmpp_config, players.clone(), rooms.clone(), metrics.clone(), storage.clone()).await?;
|
||||||
xmpp_config,
|
|
||||||
players.clone(),
|
|
||||||
rooms.clone(),
|
|
||||||
metrics.clone(),
|
|
||||||
storage.clone(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
tracing::info!("Started");
|
tracing::info!("Started");
|
||||||
|
|
||||||
sleep.await;
|
sleep.await;
|
||||||
|
|
Loading…
Reference in New Issue