Compare commits

..
33 changed files with 262 additions and 151 deletions

No files matched your search

+3 -2
View File
@@ -849,7 +849,6 @@ impl crate::Context<'_> {
get_room_state::v1::Request::new(at_event_id, room_id.clone()),
)
.await?;
let _state_lock = self.services.rooms.state.mutex.lock(&*room_id).await;
for pdu in remote_state_response.pdus.clone() {
match self
@@ -945,11 +944,13 @@ impl crate::Context<'_> {
.save_state(room_id.clone().as_ref(), new_room_state)
.await?;
let state_lock = self.services.rooms.state.mutex.lock(&*room_id).await;
info!("Forcing new room state");
self.services
.rooms
.state
.force_state(room_id.clone().as_ref(), short_state_hash, added, removed)
.force_state(room_id.clone().as_ref(), short_state_hash, added, removed, &state_lock)
.await?;
info!("Updating joined counts for room");
+10 -2
View File
@@ -773,7 +773,7 @@ impl crate::Context<'_> {
),
&user_id,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await?;
@@ -911,6 +911,14 @@ impl crate::Context<'_> {
);
let redaction_event_id = {
let state_lock = self
.services
.rooms
.state
.mutex
.lock(event.room_id_or_hash().as_str())
.await;
self.services
.rooms
.timeline
@@ -924,7 +932,7 @@ impl crate::Context<'_> {
},
event.sender(),
Some(&event.room_id_or_hash()),
None,
&state_lock,
)
.await?
};
+1 -1
View File
@@ -383,7 +383,7 @@ pub async fn full_user_deactivate(
let _ = services
.rooms
.timeline
.build_and_append_pdu(pdu, user_id, Some(room_id.as_ref()), Some(&state_lock))
.build_and_append_pdu(pdu, user_id, Some(room_id.as_ref()), &state_lock)
.await;
}
+1 -1
View File
@@ -40,7 +40,7 @@ pub(crate) async fn ban_user_route(
),
sender_user,
Some(&body.room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+2 -2
View File
@@ -177,7 +177,7 @@ async fn send_invite(
PartialPdu::state(recipient_user.to_string(), &content),
sender_user,
Some(room_id),
Some(&state_lock),
&state_lock,
)
.await?;
@@ -276,7 +276,7 @@ async fn send_invite(
PartialPdu::state(recipient_user.to_string(), &content),
sender_user,
Some(room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+1 -1
View File
@@ -48,7 +48,7 @@ pub(crate) async fn kick_user_route(
),
sender_user,
Some(&body.room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+17 -7
View File
@@ -266,9 +266,16 @@ async fn knock_room_by_id_helper(
.boxed()
.await?;
} else {
knock_room_helper_remote(services, sender_user, room_id, reason, servers)
.boxed()
.await?;
knock_room_helper_remote(
services,
sender_user,
room_id,
reason,
servers,
new_state_lock,
)
.boxed()
.await?;
}
return Ok(knock_room::v3::Response::new(room_id.to_owned()));
@@ -297,7 +304,7 @@ async fn knock_room_by_id_helper(
.boxed()
.await?;
} else {
knock_room_helper_remote(services, sender_user, room_id, reason, servers)
knock_room_helper_remote(services, sender_user, room_id, reason, servers, state_lock)
.boxed()
.await?;
}
@@ -337,7 +344,7 @@ async fn knock_room_helper_local(
PartialPdu::state(sender_user.to_string(), &content),
sender_user,
Some(room_id),
Some(&state_lock),
&state_lock,
)
.await
else {
@@ -458,6 +465,7 @@ async fn knock_room_helper_local(
&parsed_knock_pdu,
knock_event,
once(parsed_knock_pdu.event_id.borrow()),
&state_lock,
room_id,
)
.await?;
@@ -471,6 +479,7 @@ async fn knock_room_helper_remote(
room_id: &RoomId,
reason: Option<String>,
servers: &[OwnedServerName],
state_lock: RoomMutexGuard,
) -> Result {
info!("Knocking {room_id} over federation.");
@@ -632,7 +641,7 @@ async fn knock_room_helper_remote(
services
.rooms
.state
.force_state(room_id, statehash_before_knock, added, removed)
.force_state(room_id, statehash_before_knock, added, removed, &state_lock)
.await?;
let statehash_after_knock = services
@@ -657,6 +666,7 @@ async fn knock_room_helper_remote(
&parsed_knock_pdu,
knock_event,
once(parsed_knock_pdu.event_id.borrow()),
&state_lock,
room_id,
)
.await?;
@@ -667,7 +677,7 @@ async fn knock_room_helper_remote(
services
.rooms
.state
.set_room_state(room_id, statehash_after_knock);
.set_room_state(room_id, statehash_after_knock, &state_lock);
Ok(())
}
+1 -1
View File
@@ -155,7 +155,7 @@ pub async fn leave_room(
PartialPdu::state(user_id.to_string(), &content),
user_id,
Some(room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+1 -1
View File
@@ -47,7 +47,7 @@ pub(crate) async fn unban_user_route(
PartialPdu::state(body.user_id.to_string(), &current_member_content),
sender_user,
Some(&body.room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+5 -1
View File
@@ -27,6 +27,8 @@ pub(crate) async fn redact_event_route(
return Err!(Request(UserSuspended("You cannot perform this action while suspended.")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
let event_id = services
.rooms
.timeline
@@ -41,9 +43,11 @@ pub(crate) async fn redact_event_route(
},
sender_user,
Some(&body.room_id),
None,
&state_lock,
)
.await?;
drop(state_lock);
Ok(redact_event::v3::Response::new(event_id))
}
+10 -10
View File
@@ -327,7 +327,7 @@ pub(crate) async fn create_room_route(
},
sender_user,
tmp_id,
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -367,7 +367,7 @@ pub(crate) async fn create_room_route(
PartialPdu::state(sender_user.to_string(), &join_event),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -409,7 +409,7 @@ pub(crate) async fn create_room_route(
},
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -429,7 +429,7 @@ pub(crate) async fn create_room_route(
),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -452,7 +452,7 @@ pub(crate) async fn create_room_route(
),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -468,7 +468,7 @@ pub(crate) async fn create_room_route(
),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -487,7 +487,7 @@ pub(crate) async fn create_room_route(
),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -512,7 +512,7 @@ pub(crate) async fn create_room_route(
services
.rooms
.timeline
.build_and_append_pdu(pdu, sender_user, Some(&room_id), Some(&state_lock))
.build_and_append_pdu(pdu, sender_user, Some(&room_id), &state_lock)
.boxed()
.await?;
}
@@ -567,7 +567,7 @@ pub(crate) async fn create_room_route(
PartialPdu::state(String::new(), &RoomNameEventContent::new(name.clone())),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -581,7 +581,7 @@ pub(crate) async fn create_room_route(
PartialPdu::state(String::new(), &RoomTopicEventContent::new(topic.clone())),
sender_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
+9 -9
View File
@@ -123,7 +123,7 @@ async fn update_parents(
),
sender,
Some(&parent_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await
@@ -218,7 +218,7 @@ async fn update_children(
),
sender,
Some(&child_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await
@@ -246,7 +246,7 @@ async fn update_children(
),
sender,
Some(&child_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await
@@ -324,7 +324,7 @@ pub(crate) async fn upgrade_room_route(
),
sender_user,
Some(&body.room_id),
Some(&old_room_state_lock),
&old_room_state_lock,
)
.await
.map_err(|_| {
@@ -407,7 +407,7 @@ pub(crate) async fn upgrade_room_route(
PartialPdu::state(StateKey::new(), &create_event_content),
sender_user,
replacement_room_id.as_deref(),
Some(&new_room_state_lock),
&new_room_state_lock,
)
.boxed()
.await?;
@@ -453,7 +453,7 @@ pub(crate) async fn upgrade_room_route(
),
sender_user,
replacement_room_id.as_deref(),
Some(&new_room_state_lock),
&new_room_state_lock,
)
.boxed()
.await?;
@@ -527,7 +527,7 @@ pub(crate) async fn upgrade_room_route(
},
sender_user,
replacement_room_id.as_deref(),
Some(&new_room_state_lock),
&new_room_state_lock,
)
.boxed()
.await?;
@@ -572,7 +572,7 @@ pub(crate) async fn upgrade_room_route(
),
sender_user,
Some(&body.room_id),
Some(&old_room_state_lock),
&old_room_state_lock,
)
.await?;
@@ -613,7 +613,7 @@ pub(crate) async fn upgrade_room_route(
),
sender_user,
Some(&body.room_id),
Some(&old_room_state_lock),
&old_room_state_lock,
)
.boxed()
.await
+5 -1
View File
@@ -46,6 +46,8 @@ pub(crate) async fn send_message_event_route(
return Err!(Request(Forbidden("Encryption has been disabled")));
}
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
if body.event_type == MessageLikeEventType::CallInvite
&& services.rooms.directory.is_public_room(&body.room_id).await
{
@@ -112,7 +114,7 @@ pub(crate) async fn send_message_event_route(
},
sender_user,
Some(&body.room_id),
None,
&state_lock,
)
.await?;
@@ -123,6 +125,8 @@ pub(crate) async fn send_message_event_route(
event_id.as_bytes(),
);
drop(state_lock);
Ok(send_message_event::v3::Response::new(event_id))
}
+2 -7
View File
@@ -1,10 +1,7 @@
use std::{borrow::Borrow, iter::once};
use axum::extract::State;
use conduwuit::{
Err, Event, Result, info,
utils::stream::{BroadbandExt, ReadyExt},
};
use conduwuit::{Err, Event, Result, info, utils::stream::ReadyExt};
use futures::StreamExt;
use ruma::api::federation::authorization::get_event_authorization;
@@ -67,9 +64,7 @@ pub(crate) async fn get_event_authorization_route(
.auth_chain
.event_ids_iter(&body.room_id, once(body.event_id.borrow()))
.ready_filter_map(Result::ok)
.broad_filter_map(
|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() },
)
.filter_map(|id| async move { services.rooms.timeline.get_pdu_json(&id).await.ok() })
.then(|pdu| services.sending.convert_to_outgoing_federation_event(pdu))
.collect()
.await;
+2 -15
View File
@@ -1,7 +1,7 @@
use std::collections::{HashSet, VecDeque};
use axum::extract::State;
use conduwuit::{Err, Event, Result, debug, debug_warn, info, trace, utils::to_canonical_object};
use conduwuit::{Err, Event, Result, debug, info, trace, utils::to_canonical_object, warn};
use ruma::{OwnedEventId, api::federation::event::get_missing_events};
use serde_json::value::RawValue;
use service::rooms::event_handler::GET_MISSING_EVENTS_MAX_BATCH_SIZE;
@@ -44,13 +44,6 @@ pub(crate) async fn get_missing_events_route(
.unwrap_or(10)
.min(GET_MISSING_EVENTS_MAX_BATCH_SIZE);
if body.latest_events.len() > limit {
return Err!(Request(InvalidParam("Too many latest_events")));
}
if body.earliest_events.len() > limit {
return Err!(Request(InvalidParam("Too many earliest_events")));
}
let room_version = services.rooms.state.get_room_version(&body.room_id).await?;
let mut queue: VecDeque<OwnedEventId> = VecDeque::from(body.latest_events.clone());
@@ -71,9 +64,7 @@ pub(crate) async fn get_missing_events_route(
let mut pdu = match services.rooms.timeline.get_pdu(&next_event_id).await {
| Ok(pdu) => pdu,
| Err(e) => {
debug_warn!(
"could not find event {next_event_id} while walking missing events: {e}"
);
warn!("could not find event {next_event_id} while walking missing events: {e}");
continue;
},
};
@@ -83,10 +74,6 @@ pub(crate) async fn get_missing_events_route(
body.room_id
)));
}
if pdu.depth < body.min_depth {
debug!(%next_event_id, %pdu.depth, %body.min_depth, "event is below minimum depth, not traversing");
continue;
}
if services
.rooms
.pdu_metadata
+1 -1
View File
@@ -151,7 +151,7 @@ pub(crate) async fn create_join_event_template_route(
),
&body.user_id,
Some(&body.room_id),
Some(&state_lock),
&state_lock,
)
.await?;
drop(state_lock);
+1 -1
View File
@@ -107,7 +107,7 @@ pub(crate) async fn create_knock_event_template_route(
),
&body.user_id,
Some(&body.room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+1 -1
View File
@@ -59,7 +59,7 @@ pub(crate) async fn create_leave_event_template_route(
),
&body.user_id,
Some(&body.room_id),
Some(&state_lock),
&state_lock,
)
.await?;
+9 -9
View File
@@ -75,7 +75,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
PartialPdu::state(String::new(), &create_content),
server_user,
room_id.as_deref(),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -100,7 +100,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -135,7 +135,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
PartialPdu::state(String::new(), &power_levels_content),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -148,7 +148,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
PartialPdu::state(String::new(), &RoomJoinRulesEventContent::new(JoinRule::Invite)),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -164,7 +164,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -180,7 +180,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -194,7 +194,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
PartialPdu::state(String::new(), &RoomNameEventContent::new(room_name)),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -207,7 +207,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
PartialPdu::state(String::new(), &RoomTopicEventContent::markdown(room_topic)),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
@@ -223,7 +223,7 @@ pub async fn create_admin_room(services: &Services) -> Result {
PartialPdu::state(String::new(), &alias_content),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.boxed()
.await?;
+6 -6
View File
@@ -56,7 +56,7 @@ impl super::Service {
),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await?;
@@ -70,7 +70,7 @@ impl super::Service {
),
user_id,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await?;
} else {
@@ -84,7 +84,7 @@ impl super::Service {
),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await?;
}
@@ -116,7 +116,7 @@ impl super::Service {
PartialPdu::state(String::new(), &room_power_levels),
server_user,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await?;
@@ -196,7 +196,7 @@ impl super::Service {
PartialPdu::state(String::new(), &room_power_levels),
self.services.globals.server_user.as_ref(),
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await
.inspect_err(|e| {
@@ -243,7 +243,7 @@ impl super::Service {
PartialPdu::state(user_id.to_string(), &member_content),
self.services.globals.server_user.as_ref(),
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await
.map(|_| ())
+11 -4
View File
@@ -32,7 +32,7 @@ use tokio::sync::RwLock;
use crate::{
Dep, account_data, config, globals,
media::{MXC_LENGTH, mxc::Mxc},
rooms,
rooms::{self, state::RoomMutexGuard},
};
pub struct Service {
@@ -492,6 +492,7 @@ impl Service {
) -> Result<()> {
assert!(self.user_is_admin(user_id).await, "sender is not admin");
let state_lock = self.services.state.mutex.lock(room_id).await;
if let Err(e) = self
.services
.timeline
@@ -499,11 +500,11 @@ impl Service {
PartialPdu::timeline(&self.text_or_file(content).await),
user_id,
Some(room_id),
None,
&state_lock,
)
.await
{
self.handle_response_error(e, room_id, user_id)
self.handle_response_error(e, room_id, user_id, &state_lock)
.boxed()
.await
.unwrap_or_else(default_log);
@@ -517,6 +518,7 @@ impl Service {
e: Error,
room_id: &RoomId,
user_id: &UserId,
state_lock: &RoomMutexGuard,
) -> Result<()> {
error!("Failed to build and append admin room response PDU: \"{e}\"");
let content = RoomMessageEventContent::text_plain(format!(
@@ -526,7 +528,12 @@ impl Service {
self.services
.timeline
.build_and_append_pdu(PartialPdu::timeline(&content), user_id, Some(room_id), None)
.build_and_append_pdu(
PartialPdu::timeline(&content),
user_id,
Some(room_id),
state_lock,
)
.await?;
Ok(())
@@ -325,6 +325,7 @@ impl super::Service {
trace!(%user_id, "user does not have power level to send dummy event, skipping");
continue;
}
let state_lock = self.services.state.mutex.lock(room_id).await;
if self
.services
.timeline
@@ -335,7 +336,7 @@ impl super::Service {
},
&user_id,
Some(room_id),
None,
&state_lock,
)
.await
.inspect(|_| debug!(sender=%user_id, "Successfully sent a dummy event"))
@@ -178,7 +178,7 @@ impl super::Service {
/// Returns a boolean indicating whether the event is authorised, and also
/// the resolved state before the event for later use. Returns an error if
/// state fetching or auth checking fails.
pub(super) async fn state_before_check_5(
pub async fn state_before_check_5(
&self,
incoming_pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
@@ -203,7 +203,7 @@ impl super::Service {
.await?;
let state_before = match state_before {
| Some(s) => s,
| None => {
| None if !self.services.globals.server_is_ours(origin) => {
trace!("Could not calculate incoming state, asking remote {origin} for it");
self.fetch_state(origin, create_event, &room_id, incoming_pdu.event_id())
.await
@@ -211,6 +211,11 @@ impl super::Service {
debug_error!("Could not fetch state from {origin}: {e}");
})?
},
| None => {
// This should be impossible as we must know all prev_events
// locally, meaning we can resolve the state?
return Err!("Could not resolve state before new event");
},
};
if state_before.is_empty()
@@ -257,7 +262,7 @@ impl super::Service {
///
/// Returns a boolean indicating whether the event is authorised, or an
/// error if the auth check fails.
pub(super) async fn current_state_check_6(
pub async fn current_state_check_6(
&self,
incoming_pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
@@ -21,7 +21,7 @@ impl super::Service {
/// If we do not know enough information to resolve the state, `Ok(None)` is
/// returned, and the caller will have to figure it out some other way (e.g.
/// by fetching the state from a remote server).
pub(super) async fn state_before_incoming<Pdu>(
pub async fn state_before_incoming<Pdu>(
&self,
incoming_pdu: &Pdu,
room_version_rules: &RoomVersionRules,
@@ -29,7 +29,10 @@ impl super::Service {
where
Pdu: Event + Send + Sync,
{
if incoming_pdu.prev_events().count() == 1 {
let prev_count = incoming_pdu.prev_events().count();
if prev_count == 0 {
Ok(Some(HashMap::new()))
} else if incoming_pdu.prev_events().count() == 1 {
self.state_before_incoming_degree_one(incoming_pdu).await
} else {
self.state_before_incoming_resolved(incoming_pdu, room_version_rules)
@@ -60,14 +60,6 @@ impl super::Service {
let timer = Instant::now();
let min_depth = self.services.metadata.get_mindepth(room_id).await;
let room_version_rules = get_room_version_rules(create_event)?;
// We lock the room here to prevent the current state from changing
// beneath us mid-check.
let state_lock = if incoming_pdu.state_key.is_some() || incoming_pdu.prev_events.len() > 1
{
Some(self.services.state.mutex.lock(room_id).await)
} else {
None
};
// We now need to resolve the state before the event so that we can
// perform PDU check 5 (event auth passes based on state before the
@@ -89,6 +81,14 @@ impl super::Service {
// that it passes based on the *current* room state (state across all
// forward extremities). If it doesn't, we accept it, but soft-fail
// it, and this prevents it being promoted.
// We lock the room here to prevent the current state from changing
// beneath us mid-check.
trace!(
room_id = %room_id,
"Locking the room"
);
let state_lock = self.services.state.mutex.lock(room_id).await;
let passes_current_state = self
.current_state_check_6(&incoming_pdu, &room_version_rules, create_event)
.await
@@ -175,9 +175,9 @@ impl super::Service {
&room_version_rules,
state_before,
should_soft_fail,
&state_lock,
)
.await?;
drop(state_lock);
if should_soft_fail {
debug_info!(
@@ -193,6 +193,7 @@ impl super::Service {
}
// Event has passed all auth/stateres checks
drop(state_lock);
if incoming_pdu.depth > min_depth && incoming_pdu.state_key().is_some() {
self.services
.metadata
+7 -5
View File
@@ -228,7 +228,7 @@ impl Service {
// If we aren't participating in the room, or failed to join locally,
// try to join over federation.
self.join_remote_room(sender_user, room_id, reason, &servers)
self.join_remote_room(sender_user, room_id, reason, &servers, &state_lock)
.boxed()
.await?;
@@ -291,7 +291,7 @@ impl Service {
PartialPdu::state(sender_user.to_string(), &content),
sender_user,
Some(room_id),
Some(state_lock),
state_lock,
)
.await?;
@@ -305,6 +305,7 @@ impl Service {
room_id: &RoomId,
reason: Option<String>,
servers: &[&OwnedServerName],
state_lock: &RoomMutexGuard,
) -> Result {
// public so the admin command force-join-room-remotely works
info!("Joining {room_id} over federation.");
@@ -663,7 +664,7 @@ impl Service {
debug!("Forcing state for new room");
self.services
.state
.force_state(room_id, statehash_before_join, added, removed)
.force_state(room_id, statehash_before_join, added, removed, state_lock)
.await?;
debug!("Updating joined counts for new room");
@@ -685,6 +686,7 @@ impl Service {
&parsed_join_pdu,
join_event,
once(parsed_join_pdu.event_id.as_ref()),
state_lock,
room_id,
)
.await?;
@@ -699,7 +701,7 @@ impl Service {
// exist
self.services
.state
.set_room_state(room_id, statehash_after_join);
.set_room_state(room_id, statehash_after_join, state_lock);
if !resident_before {
// NOTE: We replace local extremities for this room if we were not a
// resident before. We might be doing a remote join to satisfy
@@ -709,7 +711,7 @@ impl Service {
info!("Replacing local forward extremities");
self.services
.state
.set_forward_extremities(room_id, once(parsed_join_pdu.event_id()))
.set_forward_extremities(room_id, once(parsed_join_pdu.event_id()), state_lock)
.await;
}
drop(cork);
+16 -5
View File
@@ -102,6 +102,7 @@ impl Service {
shortstatehash: u64,
statediffnew: Arc<CompressedState>,
_statediffremoved: Arc<CompressedState>,
state_lock: &RoomMutexGuard,
) -> Result {
let event_ids = statediffnew
.iter()
@@ -138,7 +139,7 @@ impl Service {
self.services.state_cache.update_joined_count(room_id).await;
self.set_room_state(room_id, shortstatehash);
self.set_room_state(room_id, shortstatehash, state_lock);
self.services.sync.wake_all_joined(room_id).await;
@@ -362,8 +363,14 @@ impl Service {
}
/// Set the state hash to a new version, but does not update state_cache.
#[tracing::instrument(skip(self), level = "debug")]
pub fn set_room_state(&self, room_id: &RoomId, shortstatehash: u64) {
#[tracing::instrument(skip(self, _mutex_lock), level = "debug")]
pub fn set_room_state(
&self,
room_id: &RoomId,
shortstatehash: u64,
// Take mutex guard to make sure users get the room state mutex
_mutex_lock: &RoomMutexGuard,
) {
const BUFSIZE: usize = size_of::<u64>();
self.db
@@ -413,8 +420,12 @@ impl Service {
.ignore_err()
}
pub async fn set_forward_extremities<'a, I>(&'a self, room_id: &'a RoomId, event_ids: I)
where
pub async fn set_forward_extremities<'a, I>(
&'a self,
room_id: &'a RoomId,
event_ids: I,
_state_lock: &'a RoomMutexGuard,
) where
I: Iterator<Item = &'a EventId> + Send + 'a,
{
let prefix = (room_id, Interfix);
+1 -1
View File
@@ -146,7 +146,7 @@ impl super::Service {
),
sender,
Some(room_id),
Some(state_lock),
state_lock,
)
.await
.is_ok()
+19 -7
View File
@@ -14,6 +14,7 @@ use conduwuit::{
trace,
utils::{
IterStream, TryFutureExtExt,
mutex_map::Guard,
stream::{BroadbandExt, ReadyExt},
},
warn,
@@ -26,8 +27,8 @@ use conduwuit_core::{
};
use futures::{FutureExt, StreamExt, TryFutureExt, pin_mut};
use ruma::{
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedServerName, RoomId,
RoomVersionId, ServerName, UserId,
CanonicalJsonObject, CanonicalJsonValue, EventId, OwnedEventId, OwnedRoomId, OwnedServerName,
RoomId, RoomVersionId, ServerName, UserId,
events::{
AnySyncTimelineEvent, GlobalAccountDataEventType, TimelineEventType,
push_rules::PushRulesEvent,
@@ -42,7 +43,7 @@ use ruma::{
serde::Raw,
};
use super::{ExtractBody, ExtractRelatesTo, ExtractRelatesToEventId};
use super::{ExtractBody, ExtractRelatesTo, ExtractRelatesToEventId, RoomMutexGuard};
use crate::{
appservice::RegistrationInfo,
rooms::state_compressor::{CompressedState, HashSetCompressStateEvent},
@@ -58,6 +59,7 @@ impl super::Service {
room_version_rules: &RoomVersionRules,
state_before: HashMap<u64, OwnedEventId>,
should_soft_fail: bool,
state_lock: &'a RoomMutexGuard,
) -> Result<Option<RawPduId>> {
let room_id = pdu.room_id_or_hash();
@@ -102,11 +104,18 @@ impl super::Service {
.get_forward_extremities(&room_id)
.collect()
.await,
state_lock,
)
.await?;
let pdu_id = self
.append_pdu(pdu, pdu_json, extremities.iter().map(Borrow::borrow), &room_id)
.append_pdu(
pdu,
pdu_json,
extremities.iter().map(Borrow::borrow),
state_lock,
&room_id,
)
.await?;
// Process admin commands for federation events
@@ -157,10 +166,11 @@ impl super::Service {
room_version_rules: &RoomVersionRules,
state_before: HashMap<u64, OwnedEventId>,
current_extremities: Vec<OwnedEventId>,
state_lock: &Guard<OwnedRoomId, ()>,
) -> Result<Vec<OwnedEventId>> {
if incoming_pdu.state_key().is_some() {
debug!("Event is a state-event. Deriving new room state");
self.derive_new_state(incoming_pdu, room_version_rules, state_before)
self.derive_new_state(incoming_pdu, room_version_rules, state_before, state_lock)
.await?;
}
@@ -259,6 +269,7 @@ impl super::Service {
incoming_pdu: &PduEvent,
room_version_rules: &RoomVersionRules,
state_before: HashMap<u64, OwnedEventId>,
state_lock: &Guard<OwnedRoomId, ()>,
) -> Result {
let room_id = incoming_pdu.room_id_or_hash();
// We also add state after incoming event to the fork states
@@ -291,7 +302,7 @@ impl super::Service {
self.services
.state
.force_state(&room_id, shortstatehash, added, removed)
.force_state(&room_id, shortstatehash, added, removed, state_lock)
.await
}
@@ -341,6 +352,7 @@ impl super::Service {
pdu: &'a PduEvent,
mut pdu_json: CanonicalJsonObject,
leaves: Leaves,
state_lock: &'a RoomMutexGuard,
room_id: &'a RoomId,
) -> Result<RawPduId>
where
@@ -375,7 +387,7 @@ impl super::Service {
trace!("setting forward extremities");
self.services
.state
.set_forward_extremities(room_id, leaves)
.set_forward_extremities(room_id, leaves, state_lock)
.await;
let insert_lock = self.mutex_insert.lock(room_id).await;
+91 -18
View File
@@ -1,6 +1,6 @@
use std::{collections::HashSet, iter::once};
use conduwuit::trace;
use conduwuit::{Pdu, err, pdu::RawId, trace};
use conduwuit_core::{
Err, Result,
matrix::{event::Event, pdu::PartialPdu},
@@ -8,7 +8,7 @@ use conduwuit_core::{
};
use futures::{FutureExt, StreamExt};
use ruma::{
EventId, OwnedEventId, OwnedServerName, RoomId, UserId,
CanonicalJsonObject, EventId, OwnedEventId, OwnedServerName, RoomId, RoomVersionId, UserId,
events::{
TimelineEventType,
room::{
@@ -17,6 +17,7 @@ use ruma::{
},
},
};
use serde::Deserialize;
use super::{ExtractBody, RoomMutexGuard};
@@ -30,7 +31,7 @@ impl super::Service {
partial_pdu: PartialPdu,
sender: &UserId,
room_id: Option<&RoomId>,
state_lock: Option<&RoomMutexGuard>,
state_lock: &RoomMutexGuard,
) -> Result<OwnedEventId> {
let (pdu, pdu_json) = self
.create_hash_and_sign_event(partial_pdu, sender, room_id, state_lock)
@@ -43,6 +44,13 @@ impl super::Service {
// If redaction event is not authorized, do not append it to the
// timeline
let _room_version_rules = self
.services
.state
.get_room_version(&room_id)
.await?
.rules()
.expect("room version must have algorithm rules");
if *pdu.kind() == TimelineEventType::RoomRedaction {
use ruma::RoomVersionId::*;
trace!("Running redaction checks for room {room_id}");
@@ -106,16 +114,6 @@ impl super::Service {
.await;
}
// We append to state before appending the pdu, so we don't have a
// moment in time with the pdu without it's state. This is okay
// because append_pdu can't fail.
trace!("Appending {} state for room {room_id}", pdu.event_id());
let statehashid = self.services.state.append_to_state(&pdu, &room_id).await?;
trace!("State hash ID for {room_id}: {statehashid:?}");
// prev_events is capped at the room version's limit, so this PDU does
// not necessarily reference every extremity. Any it did not reference
// is still a head of the DAG and has to be kept.
let prev_events: HashSet<&EventId> = pdu.prev_events().collect();
let unreferenced: Vec<OwnedEventId> = self
.services
@@ -125,19 +123,37 @@ impl super::Service {
.collect()
.await;
trace!("Generating raw ID for PDU {}", pdu.event_id());
let pdu_id = self
.append_pdu(
// We set the event's state before we actually append the PDU so that
// there isn't a moment in time where the PDU exists without its
// associated state.
let pdu_id = if pdu.prev_events.len() <= 1 {
// We can simply append the event to the current state in this case,
// and skip state resolution.
let statehashid = self.services.state.append_to_state(&pdu, &room_id).await?;
self.services
.state
.set_room_state(&room_id, statehashid, state_lock);
self.append_pdu(
&pdu,
pdu_json,
unreferenced
.iter()
.map(AsRef::as_ref)
.chain(once(pdu.event_id())),
state_lock,
&room_id,
)
.boxed()
.await?;
.await
.expect("append_pdu should be infallible")
} else {
// Otherwise, we have to resolve the state across the prev events
// and go through append_incoming_pdu. Despite checking auth events,
// we now have to do PDU check 5 to make sure we even
// want to keep this event based on the state before it.
self.resolve_and_append(&room_id, &pdu, pdu_json, state_lock)
.await?
};
// Process admin commands for locally sent events
if *pdu.kind() == TimelineEventType::RoomMessage {
@@ -163,7 +179,6 @@ impl super::Service {
// a moment in time where events in the current room state do not
// exist
trace!("Setting room state for room {room_id}");
self.services.state.set_room_state(&room_id, statehashid);
self.services.sync.wake_all_joined(&room_id).await;
@@ -290,4 +305,62 @@ impl super::Service {
Ok(())
}
/// Resolves the state before a new event and runs it through
/// append_incoming_pdu to persist the state update, instead of simply
/// appending it to the current state.
async fn resolve_and_append(
&self,
room_id: &RoomId,
pdu: &Pdu,
pdu_json: CanonicalJsonObject,
state_lock: &RoomMutexGuard,
) -> Result<RawId> {
let create_event =
if pdu.kind == TimelineEventType::RoomCreate && pdu.state_key() == Some("") {
pdu
} else {
&self
.services
.state_accessor
.get_room_create_event(room_id)
.await
};
let room_version_rules = create_event
.get_content::<ExtractRoomVersion>()?
.room_version
.rules()
.ok_or_else(|| err!("Unsupported room version"))?;
let (ok, state_before) = self
.services
.event_handler
.state_before_check_5(
pdu,
&room_version_rules,
create_event,
self.services.globals.server_name(),
)
.await?;
if !ok {
return Err!(Request(Forbidden("Event is not authorised")));
}
self.append_incoming_pdu(
pdu,
pdu_json,
&room_version_rules,
state_before,
false,
state_lock,
)
.boxed()
.await
.transpose()
.expect("Only soft-failed events cannot return a PduId, which is impossible in this path")
}
}
#[derive(Deserialize)]
struct ExtractRoomVersion {
room_version: RoomVersionId,
}
+2 -15
View File
@@ -84,7 +84,7 @@ impl super::Service {
partial_pdu: PartialPdu,
sender: &UserId,
room_id: Option<&RoomId>,
mutex_lock: Option<&RoomMutexGuard>,
_mutex_lock: &RoomMutexGuard,
) -> Result<(PduEvent, RoomVersionRules)> {
let PartialPdu {
event_type,
@@ -95,19 +95,6 @@ impl super::Service {
redacts,
timestamp,
} = partial_pdu;
#[cfg(not(feature = "release_max_log_level"))]
if state_key.is_some() && mutex_lock.is_none() {
return Err!(error!(
?event_type,
?content,
?sticky,
?unsigned,
?state_key,
?redacts,
?timestamp,
"Attempted to build a state event without a state mutex lock"
));
}
trace!(
"Creating event of type {} in room {}",
@@ -300,7 +287,7 @@ impl super::Service {
partial_pdu: PartialPdu,
sender: &UserId,
room_id: Option<&RoomId>,
mutex_lock: Option<&RoomMutexGuard>,
mutex_lock: &RoomMutexGuard,
) -> Result<(PduEvent, CanonicalJsonObject)> {
if !self.services.globals.user_is_local(sender) {
return Err!(Request(Forbidden("Sender must be a local user")));
+1 -1
View File
@@ -61,7 +61,7 @@ impl super::Service {
},
sender,
Some(room_id),
Some(state_lock),
state_lock,
)
.await?;
+1 -1
View File
@@ -191,7 +191,7 @@ impl super::Service {
PartialPdu::state(user_id.to_string(), &current_membership),
user_id,
Some(&room_id),
Some(&state_lock),
&state_lock,
)
.await;
}